PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Tuesday, May 10, 2022

[FIXED] Why does CroppedBitmap result in an invisible image?

 May 10, 2022     .net-core, c#, image, wpf     No comments   

Issue

I am attempting to use CroppedBitmap to display a portion of a PNG file on a WPF Image element.

As a test, I have the following code:

BitmapImage StandardTilesetImage = new BitmapImage();
StandardTilesetImage.BeginInit();
StandardTilesetImage.CacheOption = BitmapCacheOption.OnLoad;
StandardTilesetImage.UriSource = new Uri(pngFilePath, UriKind.Relative);
StandardTilesetImage.EndInit();

// TestImage is an Image object defined in XAML
TestImage.Source = StandardTilesetImage;

This produces the expected results - the image displays correctly:

enter image description here

For reference the pngFilePath is a string pointing to the absolute location (c:/etc/etc/StandardTilesetIcons.png) which is a 512x512 PNG:

enter image description here

If I modify the code above to clip a part of the PNG (such as drawing the top-left 64x64 area), the TestImage no longer displays anything.

BitmapImage StandardTilesetImage = new BitmapImage();
StandardTilesetImage.BeginInit();
StandardTilesetImage.CacheOption = BitmapCacheOption.OnLoad;
StandardTilesetImage.UriSource = new Uri(pngFilePath, UriKind.Relative);
StandardTilesetImage.EndInit();

CroppedBitmap croppedBitmap = new CroppedBitmap();
croppedBitmap.SourceRect = new Int32Rect(0,0,64, 64);
croppedBitmap.Source = StandardTilesetImage;
TestImage.Source = croppedBitmap;

enter image description here

I would expect to see a portion of the PNG in my TestImage object. Why is nothing showing up?


Solution

Just like BitmapImage, CroppedBitmap implements the ISupportInitialize interface, which means that when you create an instance by the default constructor, you have to call the BeginInit() and EndInit() methods before and after setting any of its properties.

Alternatively, use the appropriate constructors with parameters provided by both classes:

BitmapImage standardTilesetImage = new BitmapImage(
    new Uri(pngFilePath, UriKind.RelativeOrAbsolute));

CroppedBitmap croppedBitmap = new CroppedBitmap(
    standardTilesetImage, new Int32Rect(0,0,64, 64));

TestImage.Source = croppedBitmap;


Answered By - Clemens
Answer Checked By - Katrina (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing