gpt4 book ai didi

c# - 将 PNG 字节数组转换为 JPEG 字节数组

转载 作者:太空宇宙 更新时间:2023-11-03 20:13:05 24 4
gpt4 key购买 nike

我使用以下代码将 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();
}
}

最佳答案

下面是一段代码,用于获取任何格式的字节数组并将其转换为 JPG 格式的字节数组:

byte[] jpgImageBytes = null;
using (var origImageStream = new MemoryStream(image))
using (var jpgImageStream = new MemoryStream())
{
var jpgImage = System.Drawing.Image.FromStream(origImageStream);
jpgImage.Save(jpgImageStream, System.Drawing.Imaging.ImageFormat.Jpeg);
jpgImageBytes = jpgImageStream.ToArray();
jpgImage.Dispose();
}

关于c# - 将 PNG 字节数组转换为 JPEG 字节数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18736901/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com