【问题标题】:How achieve Image.Clone() in WPF?如何在 WPF 中实现 Image.Clone()?
【发布时间】:2009-04-28 14:50:01
【问题描述】:

我从 db 获得一个字节数组 (byte[]) 并使用以下方法渲染到图像控件中:

    public Image BinaryImageFromByteConverter(byte[] valueImage)
    {
        Image img = new Image();
        byte[] bytes = valueImage as byte[];
        MemoryStream stream = new MemoryStream(bytes);
        BitmapImage image = new BitmapImage();
        image.BeginInit();
        image.StreamSource = stream;
        image.EndInit();
        img.Source = image;
        img.Height = 240;
        img.Width = 240;
        return img;
    }

现在已经渲染了,我想将 Image.Source 从 Image(控件)“复制”到另一个元素,例如:Paragraph..

paragraph1.Inlines.Add(new InlineUIContainer(ImageOne));

但什么都没有出现,我尝试使用 ImageOne.Source 创建一个新图像,但我刚刚找到了这个带有 Uri(@"path") 的示例,我无法应用此方法,因为我的 BitmapImage 来自 byte[] 类型

Image img = new Image();
img.Source = new BitmapImage(new Uri(@"c:\icons\A.png"));

请帮忙解决这个问题,谢谢!

【问题讨论】:

  • 我不建议(反)序列化流中的图像/任何不(反)序列化像素格式、宽度、高度、步幅的图像。 - 这样做是一个漏洞。
  • 如果你使用BitmapSource作为图片,你可以读取缓冲区并从缓冲区中创建一个新的BitmapSource。

标签: wpf image-processing


【解决方案1】:

只需创建一个新的 Image 元素并将其源设置为相同的 BitmapImage:

byte[] imageInfo = File.ReadAllBytes("IMG_0726.JPG");

BitmapImage image;

using (MemoryStream imageStream = new MemoryStream(imageInfo))
{
    image = new BitmapImage();
    image.BeginInit();
    image.CacheOption = BitmapCacheOption.OnLoad;
    image.StreamSource = imageStream;
    image.EndInit();
}

this.mainImage.Source = image;
this.secondaryImage.Source = image;

如果您只是将一个来源复制到另一个来源,它也可以工作:

this.mainImage.Source = image;
this.secondaryImage.Source = this.mainImage.Source;

【讨论】:

  • 您不能以这种方式从图像复制源,您必须先断开媒体与第一个的连接,然后再尝试将相同的对象附加到第二个。
  • 您可以使用 BitmapCacheOption.OnLoad。它不会锁定文件。我已经测试了代码并且可以正常工作。
猜你喜欢
  • 2012-06-07
  • 1970-01-01
  • 2021-08-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-07-18
  • 1970-01-01
  • 2018-05-30
相关资源
最近更新 更多