首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >BitmapImage to byte[] - C# web

BitmapImage to byte[] - C# web
EN

Stack Overflow用户
提问于 2017-08-24 09:22:42
回答 4查看 1K关注 0票数 0

我需要在一个BitmapImage中转换一个byte[],但是我找不到如何在C# web中实现它。我找到了一些示例,但它们都不起作用(JpegBitmapEncoder不存在,BitmapImageObject.StreamSource不存在,没有以BitmapImage作为参数的WriteableBitmap构造函数,Extensions.SaveJpeg(参数)不存在.)。

我发现的例子:

构造函数新WriteableBitmap(bitmapImage)不存在。

代码语言:javascript
运行
复制
public static byte[] ConvertToBytes(this BitmapImage bitmapImage)
{
    byte[] data;
    // Get an Image Stream
    using (MemoryStream ms = new MemoryStream())
    {
        WriteableBitmap btmMap = new WriteableBitmap(bitmapImage);

        // write an image into the stream
        Extensions.SaveJpeg(btmMap, ms,
            bitmapImage.PixelWidth, bitmapImage.PixelHeight, 0, 100);

        // reset the stream pointer to the beginning
        ms.Seek(0, 0);
        //read the stream into a byte array
        data = new byte[ms.Length];
        ms.Read(data, 0, data.Length);
    }
    //data now holds the bytes of the image
    return data;
}

新的System.Windows.Media.Imaging.Extensions.SaveJpeg (WriteableBitmap)并不存在。

代码语言:javascript
运行
复制
public static byte[] ImageToBytes(BitmapImage img)
{
    using (MemoryStream ms = new MemoryStream())
    {
        WriteableBitmap btmMap = new WriteableBitmap(img);
        System.Windows.Media.Imaging.Extensions.SaveJpeg(btmMap, ms, img.PixelWidth, img.PixelHeight, 0, 100);
        img = null;
        return ms.ToArray();
    }
}

imageSource.StreamSource不存在。

代码语言:javascript
运行
复制
public static byte[] ImageToByte(BitmapImage imageSource)
{
    Stream stream = imageSource.StreamSource;
    Byte[] buffer = null;
    if (stream != null && stream.Length > 0)
    {
        using (BinaryReader br = new BinaryReader(stream))
        {
            buffer = br.ReadBytes((Int32)stream.Length);
        }
    }

    return buffer;
}

JpegBitmapEncoder不存在。

代码语言:javascript
运行
复制
byte[] data;
JpegBitmapEncoder encoder = new JpegBitmapEncoder();
encoder.Frames.Add(BitmapFrame.Create(bitmapImage));
using(MemoryStream ms = new MemoryStream())
{
    encoder.Save(ms);
    data = ms.ToArray();
}
EN

Stack Overflow用户

发布于 2017-08-24 09:30:23

代码语言:javascript
运行
复制
byte[] foo = System.IO.File.ReadAllBytes("bitmap path");

代码语言:javascript
运行
复制
byte[] foo;
Object obj = YourBitmap;
BinaryFormatter bf = new BinaryFormatter();
using (var ms = new MemoryStream())
{
    bf.Serialize(ms, obj);
    foo = ms.ToArray();
}

代码语言:javascript
运行
复制
ImageConverter foocon = new ImageConverter();
byte[] foo = (byte[])foocon.ConvertTo(YourBitmap, typeof(byte[]));

代码语言:javascript
运行
复制
MemoryStream ms = new MemoryStream();
Bitmap.Save(ms, YourBitmap.RawFormat);
byte[] foo = ms.ToArray();
票数 1
EN
查看全部 4 条回答
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/45857745

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档