将位图转换为字节数组 [英] Convert a bitmap into a byte array

查看:36
本文介绍了将位图转换为字节数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用 C#,是否有比保存到临时文件并使用 读取结果更好的方法将 Windows Bitmap 转换为 byte[]文件流?

Using C#, is there a better way to convert a Windows Bitmap to a byte[] than saving to a temporary file and reading the result using a FileStream?

推荐答案

有几种方法.

图像转换器

public static byte[] ImageToByte(Image img)
{
    ImageConverter converter = new ImageConverter();
    return (byte[])converter.ConvertTo(img, typeof(byte[]));
}

这个很方便,因为它不需要很多代码.

This one is convenient because it doesn't require a lot of code.

内存流

public static byte[] ImageToByte2(Image img)
{
    using (var stream = new MemoryStream())
    {
        img.Save(stream, System.Drawing.Imaging.ImageFormat.Png);
        return stream.ToArray();
    }
}

这与您正在执行的操作相同,只是文件保存在内存中而不是磁盘中.虽然更多的代码您可以选择 ImageFormat 并且可以在保存到内存或磁盘之间轻松修改.

This one is equivalent to what you are doing, except the file is saved to memory instead of to disk. Although more code you have the option of ImageFormat and it can be easily modified between saving to memory or disk.

来源:http://www.vcskicks.com/image-to-byte.php

这篇关于将位图转换为字节数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆