how to get BitmapImage in codebehind from the image tag in xaml in wpf/silverlight

后端 未结 2 1949
难免孤独
难免孤独 2021-01-24 07:36

i dont have a problem with binding a bitmapimage to image tag in codebehind for eg.

BitmapImage image = new BitmapImage();
imagetaginxaml.Source = image; // this         


        
相关标签:
2条回答
  • 2021-01-24 08:18

    How about using WriteableBitmap to make a copy of the image, and then using a MemoryStream to copy the original image into a copy?

    // Create a WriteableBitmap from the Image control
    WriteableBitmap bmp = new WriteableBitmap(imagetaginxaml, null);
    
    // Load the contents of a MemoryStream from the WritableBitmap
    MemoryStream m = new MemoryStream();
    bmp.SaveJpeg(m, bmp.PixelWidth, bmp.PixelHeight, 0, 100);
    
    // Read from the stream into a new BitmapImage object
    m.Position = 0;
    BitmapImage image = new BitmapImage();
    image.SetSource(m);
    
    // do something with the new BitmapImage object
    // (for example, load another image control)
    anotherimagetaginxaml.Source = image;
    
    0 讨论(0)
  • 2021-01-24 08:30

    Well, Image.Source is of type ImageSource, there is no quarantee that it will be a BitmapImage, it may be though. If the source is created by the XAML parser it will be a BitmapFrameDecode (which is an internal class). Anyway, the only save assignment is:

    ImageSource source = img.Source;
    

    otherwise you need to cast:

    BitmapImage source = (BitmapImage)img.Source;
    

    which will throw an exception if the Source is not of this type. So you can either save-cast or try-catch:

    //(Possibly check for img.Source != null first)
    BitmapImage source = img.Source as BitmapImage;
    if (source != null)
    {
         //If img.Source is not null the cast worked.
    }
    
    try
    {
        BitmapImage source = (BitmapImage)img.Source;
        //If this line is reached it worked.
    }
    catch (Exception)
    {
        //Cast failed
    }
    

    You could also check the type beforehand using img.SourceisBitmapImage.

    0 讨论(0)
提交回复
热议问题