我使用以下代码将 BitmapSource 转换为表示 png 的字节数组:
/// <summary>
/// Converts BitmapSource to a PNG Bitmap.
/// </summary>
/// <param name="source">The source object to convert.</param>
/// <returns>byte array version of passed in object.</returns>
public static byte[] ToPngBytes(this BitmapSource source)
{
// Write the source to the bitmap using a stream.
using (MemoryStream outStream = new MemoryStream())
{
// Encode to Png format.
var enc = new Media.Imaging.PngBitmapEncoder();
enc.Frames.Add(Media.Imaging.BitmapFrame.Create(source));
enc.Save(outStream);
// Return image bytes.
return outStream.ToArray();
}
}
我希望执行相同的操作,但无需先创建 BitmapSource 即可转换为 Jpeg 的字节数组。
签名应如下所示:
public static byte[] ToPngBytes(this byte[] jpegBytes)
此代码有效,但似乎效率低下,因为我必须使用可写位图来执行此操作:
private WriteableBitmap colorBitmap;
private byte[] GetCompressedImage(byte[] imageData, System.Windows.Media.PixelFormat format, int width, int height, int bytesPerPixel = sizeof(Int32))
{
// Initialise the color bitmap converter.
if (colorBitmap == null)
colorBitmap = new WriteableBitmap(width, height, 96.0, 96.0, format, null);
// Write the pixels to the bitmap.
colorBitmap.WritePixels(new Int32Rect(0, 0, width, height), imageData, width * bytesPerPixel, 0);
// Memory stream used for encoding.
using (MemoryStream memoryStream = new MemoryStream())
{
PngBitmapEncoder encoder = new PngBitmapEncoder();
// Add the frame to the encoder.
encoder.Frames.Add(BitmapFrame.Create(colorBitmap));
encoder.Save(memoryStream);
// Get the bytes.
return memoryStream.ToArray();
}
}