繁体   English   中英

将字节数组转换为灰度的jpeg

[英]Convert byte array to jpeg in grayscale

我有一个简单的Byte数组,代表灰度图像(值从0到255)

有一个例子:

Byte[] sample = new Byte[16] {
    55 ,0  ,0  ,255,
    12 ,255,75 ,255,
    255,150,19 ,255,
    42 ,255,78 ,255 };

我想将其保存为jpeg格式,但是我不知道该怎么做。

我尝试了2种方法,但是没有用。 我认为我的字节数组格式不正确,但我不知道该怎么做。

我已经试过了:

TypeConverter tc = TypeDescriptor.GetConverter(typeof(Bitmap));
Bitmap bmp = (Bitmap)tc.ConvertFrom(sample);
bmp.Save(myPath, System.Drawing.Imaging.ImageFormat.Jpeg);

和这个 :

MemoryStream str = new MemoryStream(sample);
str.Position = 0;
using (Image image = Image.FromStream(str))
{
    image.Save(myPath, System.Drawing.Imaging.ImageFormat.Jpeg);
}
BitmapImage photo = byteToImage(byte[] sample) 

此函数将字节转换为BitmapImage

public BitmapImage byteToImage(byte[] buffer)
{

 using(var ms = new MemoryStream(buffer))
 {
   var image = new BitmapImage();
   image.BeginInit();
   image.CacheOption = BitmapCacheOption.OnLoad;
   image.StreamSource =  ms;
   image.EndInit();
 }

 return image;
}

然后byteToImage将返回图像,以便您保存。

希望这可以帮助您

有了您的所有指示,我终于找到了一种方法:

public static void SaveByteArryToJpeg(string imagePath, Byte[] data, int width, int height)
{
    if (width * height != data.Length)
        throw new FormatException("Size does not match");

    Bitmap bmp = new Bitmap(width, height);

    for (int r = 0; r < height; r++)
    {
        for (int c = 0; c < width; c++)
        {
            Byte value = data[r * width + c];
            bmp.SetPixel(c, r, Color.FromArgb(value, value, value));
        }
    }

    bmp.Save(imagePath, System.Drawing.Imaging.ImageFormat.Jpeg);
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM