C#编码位图JPEG并将其保存到byte []

时间:2014-06-04 15:24:02

标签: c# encoding bitmap jpeg

我有这个代码将图像保存到磁盘

public static void SaveImage(Bitmap picture, string path)
    {

        // Comprimir
        ImageCodecInfo encoder = GetJPGEncoder();

        // Create an Encoder object based on the GUID
        // for the Quality parameter category.
        System.Drawing.Imaging.Encoder myEncoder =
            System.Drawing.Imaging.Encoder.Quality;

        // Create an EncoderParameters object.
        // An EncoderParameters object has an array of EncoderParameter
        // objects. In this case, there is only one
        // EncoderParameter object in the array.
        EncoderParameters myEncoderParameters = new EncoderParameters(1);
        EncoderParameter myEncoderParameter = new EncoderParameter(myEncoder, 50L);
        myEncoderParameters.Param[0] = myEncoderParameter;

        //picture.
        picture.Save(path, encoder, myEncoderParameters);

    }

但现在我需要将结果作为byte []。我无法找到将结果存入内存的方法,以便将其转换为byte []。我想在将文件保存到硬盘驱动器后加载文件,但这完全没必要。有谁知道我是否能做到这一点?

2 个答案:

答案 0 :(得分:1)

使用MemoryStreamSave()方法的一个重载需要Stream

答案 1 :(得分:1)

使用此:

using(var stream = new MemoryStream())
{
    picture.Save(stream, encoder, myEncoderParameters);
    return stream.ToArray();
}