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

标签 c# image-processing encoding arrays

我使用以下代码将 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/

相关文章:

c# - 只有 1 个进程显示事件并行 foreach

python - 在其他功能中使用相机时从网络摄像头拍摄快照

c# - 在 C# 中编码 XML

c# - 应该在编码中使用什么加密以及它如何影响 key 和初始化向量?

c# - JQUERY AJAX 多个级联dropdownlist select不加载问题

c# - C# 中的 Nplot 引用存在问题

image-processing - 为什么 cv::Dilate 的第三个参数失败?

opencv - 选定区域的仿射变换

python - 如何在 strptime 中使用俄语日期字符串

c# - 将集合绑定(bind)到列表控件