【问题标题】:How to send image files to/from server如何向/从服务器发送图像文件
【发布时间】:2012-12-30 10:39:09
【问题描述】:

我想实现以下两个服务: (使用 web api 处理)

  1. 从服务器获取图片。
  2. 向服务器添加新图片。

服务器将图片存储在 DB iun varbinary 中。 图片可以是bmp、jpg、ico

我的函数签名是

AddIcon(string Id, byte[] IconFile)

然后我想把它插入到数据库中。 现在,如果我通过我的 DTO 传递 BitmapImage,我需要引用许多对象,我认为这不是最佳做法。这就是为什么我更喜欢 byte[]。

  1. 有没有办法在不知道其结构的情况下将 BitmapImage 转换为 Byte[]?
  2. 在检索文件时,是否可以在不知道其结构的情况下将 Byte[] 转换回 BitmapImage(例如从磁盘加载时) 谢谢。

【问题讨论】:

  • 为什么这个问题被标记为“IIS”?您使用的是哪个数据库?

标签: c# sql-server bitmap sql-server-2012


【解决方案1】:

BitmapImage 已经过优化,它隐藏了编解码器信息等细节。您可以使用:

    public static byte[] SaveToPng(this BitmapSource bitmapSource)
    {
        return SaveWithEncoder<PngBitmapEncoder>(bitmapSource);
    }

    private static byte[] SaveWithEncoder<TEncoder>(BitmapSource bitmapSource) where TEncoder : BitmapEncoder, new()
    {
        if (bitmapSource == null) throw new ArgumentNullException("bitmapSource");

        using (var msStream = new MemoryStream())
        {
            var encoder = new TEncoder();
            encoder.Frames.Add(BitmapFrame.Create(bitmapSource));
            encoder.Save(msStream);
            return msStream.ToArray();
        }
    }


    public static BitmapSource ReadBitmap(Stream imageStream)
    {
        BitmapDecoder bdDecoder = BitmapDecoder.Create(imageStream, BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.OnLoad);
        return bdDecoder.Frames[0];
    }

【讨论】:

  • 谢谢。我可以不使用编码器吗?我不能把它当作我不知道它的类型吗?当我从磁盘加载图像时,我只是给它一个路径。那么当我从插座中得到它时,为什么我需要选择编码器呢?
  • 如何从 byte[] 返回 BitmapImage
  • BitmapImage bi = new BitmapImage(); bi.BeginInit(); bi.StreamSource = new MemoryStream(来自你的数据库的图像字节) bi.EndInit();
猜你喜欢
  • 2011-12-21
  • 2019-11-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-10-05
  • 2014-01-17
  • 2016-12-12
  • 1970-01-01
相关资源
最近更新 更多