1

次のコードを使用して、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();
        }
    }
4

2 に答える 2

3

答えには少し遅れましたが、これは他の人を助けるはずです。このソリューションでは、どのタイプの画像であるかは問題ではありません (画像である限り、任意のタイプに変換できます。

public static byte[] ConvertImageBytes(byte[] imageBytes, ImageFormat imageFormat)
        {
            byte[] byteArray = new byte[0];
            FileStream stream = new FileStream("empty." + imageFormat, FileMode.Create);
            using (MemoryStream ms = new MemoryStream(imageBytes))
            {
                stream.Write(byteArray, 0, byteArray.Length);
                byte[] buffer = new byte[16 * 1024];
                int read;
                while ((read = stream.Read(buffer, 0, buffer.Length)) > 0)
                {
                    ms.Write(buffer, 0, read);
                }
                byteArray = ms.ToArray();
                stream.Close();
                ms.Close();
            }
            return byteArray;
        }

以下のように使用します

ConvertImageBytes(imageBytes, ImageFormat.Png);
于 2014-09-25T06:29:19.390 に答える