3

I obtain an array of byte (byte[]) from db and render into a Image Control using the following method :

    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;
    }

So now that is rendered, I want to "copy" the Image.Source from Image (Control) to another element, for example : Paragraph..

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

but nothings appears, I try to create a new Image using ImageOne.Source but I just found this example with Uri(@"path"), I cant apply this method cause my BitmapImage comes from a byte[] type

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

Helps with this issue please, thanks!

Jonathan Escobedo
  • 3,977
  • 12
  • 69
  • 90
  • I do not recommend (de)serializing images from streams/whatever without (de)serializing the pixel format, width, height, stride. - Do so is an openning for bugs. – Danny Varod Oct 22 '09 at 23:36
  • If you use BitmapSource as images, you can read the buffer and create a new BitmapSource from the buffer. – Danny Varod Oct 22 '09 at 23:39

1 Answers1

3

Just create a new Image element and set its source to the same 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;

It also works if you just copy one source to the other:

this.mainImage.Source = image;
this.secondaryImage.Source = this.mainImage.Source;
RandomEngy
  • 14,931
  • 5
  • 70
  • 113
  • you cant copy the source from a Image in that way, you have to disconnect the media from the first one before try to attach the same object to the second one. – Jonathan Escobedo May 07 '09 at 19:36
  • You can with BitmapCacheOption.OnLoad. It doesn't lock the file. I've tested the code and it works. – RandomEngy May 08 '09 at 03:20