Use biggest icon in the .ico file in a pictureBox [duplicate] - c#

I have a icon which has a few different sizes (16px, 32px, 64px). I am calling ToBitmap() on it, but it is always returning the 32px image. How do I retrieve the 64px one?

Does this help?
Icon sizedIcon = new Icon(Resources.ResourceIcon, new Size(64,64));

For anyone else stumbling upon the same problem, I've found a nice little solution.
Image img = new Icon(Properties.Resources.myIcon, width, height).ToBitmap()

This is a fairly painful limitation in the ResourceManager class. Its GetObject() method doesn't provide a way to pass extra arguments that would allow selecting the returned icon by size. A workaround is to add the icon to the project instead. Use Project + Add Existing Item, select your .ico file. Select the added icon and change the Build Action property to "Embedded Resource".
You can now retrieve the desired icon with code like this:
public static Icon GetIconFromEmbeddedResource(string name, Size size) {
var asm = System.Reflection.Assembly.GetExecutingAssembly();
var rnames = asm.GetManifestResourceNames();
var tofind = "." + name + ".ICO";
foreach (string rname in rnames) {
if (rname.EndsWith(tofind, StringComparison.CurrentCultureIgnoreCase)) {
using (var stream = asm.GetManifestResourceStream(rname)) {
return new Icon(stream, size);
}
}
}
throw new ArgumentException("Icon not found");
}
Sample usage:
var icon1 = GetIconFromEmbeddedResource("ARW04LT", new Size(16, 16));
var icon2 = GetIconFromEmbeddedResource("ARW04LT", new Size(32, 32));
Beware one possible failure mode: this code assumes that the icon was added to the same assembly that contains the method.

The following sets the icon size for all the buttons in the toolbar.
It relies on the resource name being stored in the button tag.
public void SetButtons(object toolstrip, int IconWidth, int IconHeight)
{
var ts = (ToolStrip) toolstrip;
var size = new System.Drawing.Size();
size.Height = IconSize;
size.Width = IconSize;
foreach (ToolStripButton tsBtn in ts.Items)
{
tsBtn.ImageScaling = ToolStripItemImageScaling.None;
var resourcename = (String) tsBtn.Tag;
if (resourcename != null)
{
var myIcon = (Icon) Properties.Resources.ResourceManager.GetObject(resourcename);
var newIcon = new Icon(myIcon, IconWidth, IconHeight);
tsBtn.Image = newIcon.ToBitmap();
}
}
}

The size is determined when you first create the Icon instance, so you need to specify which size you want to use when you create it, using one of the Icon constructors that take a Size parameter.

internal static class IconHelper {
public static Icon GetSize(this Icon icon, int width, int height) {
return icon.GetSize(new Size(width, height));
}
public static Icon GetSize(this Icon icon, Size size) {
using(var mem = new MemoryStream()) {
icon.Save(mem);
mem.Position = 0;
return new Icon(mem, size);
}
}
}

There is no built-in method in the .Net framework that does this.
Instead, you can use this library.

Related

A problem in Xamarin.forms with an icon.png "Cannot decode image. The image must be a Bitmap" [duplicate]

I'm working with Xamarin in the part of Xamarin.Forms i need to convert a file ("image.png") to a Bitmap because when project run its enter in "break mode" and show me this message "Java.Lang.IllegalArgumentException: 'Failed to decode image. The provided image must be a Bitmap.'". So i tried to convert the file in many ways like:
1_ Using methods from System.Drawing.Bitmap but it's show this exception "This operation is not supported in this platform"
2_ Cannot use Android.Graphics because i'm working in xamarin.forms not in xamarin.android.
3_ I tried to convert the "image.png" into a base64 or byte[] array and then into a bitmap but the problem is the same like in first problem because to convert from byte[] array or base64 to a Bitmap i have use methods from System.Drawing.Bitmap.
4_ I tried using the library SkiaSharp but i don't have success because i don't found so much information about how to convert .png to SKBitmap and then convert SKBitmap to Bitmap (even i don't know if this is possible).
5_ Finally i converted "image.png" to a "image.bmp" with an app and use the file .bmp in my project but it doesn't work too.
the "image.png" i have to save in a string variable, well that's the idea.
If you have a solution with SkiaSharp o whatever i will glad
EDIT
here is a part of my code, i just save in a variable the image
Icon = "pin_blue.png";
//i can't use a path because in xamarin you have many size from the same
//image for the different size of the screen
EDIT 2 This is my method to show the pins in google maps
private void ShowPins(List<PointsOfInterest> resultPointsOfInterest)
{
if (resultPointsOfInterest != null && resultPointsOfInterest.Any())
{
var location = Geolocation.GetLastKnownLocationAsync();
PointsOfInterest position = new PointsOfInterest();
if (location != null)
{
position.ccsm0166latitud = location.Result.Latitude;
position.ccsm0166longitud = location.Result.Longitude;
}
else {
position = resultPointsOfInterest.First();
}
//Distance = Distance.FromKilometers(new Random().Next(23,35));
Distance = Distance.FromKilometers(3);
Position = new Position(position.ccsm0166latitud, position.ccsm0166longitud);
PinsFiltered= Pins = new List<PinCustom>(resultPointsOfInterest.Select(
x => new PinCustom()
{
Position =
new Position(x.ccsm0166latitud, x.ccsm0166longitud),
Address = x.ccsm0166direccion,
Label = x.ccsm0166nombre,
Type = PinType.Place,
TypePointOfInterest = x.ccsm0166tipositio,
IconBM = Int32.Parse(x.ccsm0166tipositio) == (int)PointOfInterestType.branch ? PinCustom.ConvertToBitmap("pin_blue.png") :
Int32.Parse(x.ccsm0166tipositio) == (int)PointOfInterestType.branch ? "pin_blue.png" :
Int32.Parse(x.ccsm0166tipositio) == (int)PointOfInterestType.branchWithExtendedHours ? "pin_black.png" :
Int32.Parse(x.ccsm0166tipositio) == (int)PointOfInterestType.branchWithExtendedHours2 ? "pin_black.png" :
Int32.Parse(x.ccsm0166tipositio) == (int)PointOfInterestType.branchWithExtendedHours3 ? "pin_black.png" :
Int32.Parse(x.ccsm0166tipositio) == (int)PointOfInterestType.selfServiceTerminal ? "pin_green.png" :
Int32.Parse(x.ccsm0166tipositio) == (int)PointOfInterestType.atmServBox ? "pin_yellow.png" : string.Empty
}).ToList());
}
else
{
Pins = new List<PinCustom>();
}
}
This is the class Pin where i save the image
public class PinCustom : Pin
{
public string TypePointOfInterest { get; set; }
public string Icon { get; set; }
public Bitmap { get; set; }
//Here i create this variable to save a bitmap but i don't know if i do the things well
}
this is the icon .png i want to show in googlemaps
Pin Blue Image
To open your file and convert it to byte array:
string directory = Path.Combine(Android.OS.Environment.ExternalStorageDirectory.AbsolutePath, Android.OS.Environment.DirectoryDownloads);
// or your image directory, just replace it
var stream = File.OpenWrite(Path.Combine(directory, "image.png"));
byte[] buff = ConvertStreamToByteArray(stream);
stream.Close();
public static byte[] ConvertStreamToByteArray(Stream stream)
{
byte[] byteArray = new byte[16 * 1024];
using (MemoryStream mStream = new MemoryStream())
{
int bit;
while ((bit = stream.Read(byteArray, 0, byteArray.Length)) > 0)
{
mStream.Write(byteArray, 0, bit);
}
return mStream.ToArray();
}
}
then, to pass this byte array to SKBitmap:
SKBitmap bmp = SKBitmap.Decode(buff);
EDIT:
If you want to try without ConvertStreamToByteArray():
byte[] buff = null;
stream.Write(buff, 0, buff.Length);
This Write will depend of the type of your stream. In this example, I'm using FileStream.
EDIT 2:
string resourceID = "image.png";
Assembly assembly = GetType().GetTypeInfo().Assembly;
using (Stream stream = assembly.GetManifestResourceStream(resourceID))
{
resourceBitmap = SKBitmap.Decode(stream);
SKBitmap bmp = SKImage.FromBitmap(resourceBitmap);
}
and then you can use this bitmap to draw and fill your SKCanvas:
canvas.DrawBitmap(bmp, 0, 0);
Use ffmpeg
command for this: ffmpeg -i image.png image.bmp
i have 5 types of pins (pins are the image .png) when i put the pins
in format .png
if you want to custom the pins in your map, you can simply use Custom Renderers to achieve this.
The icon used to represent a marker can be customized by calling the MarkerOptions.SetIcon method. This can be accomplished by overriding the CreateMarker method, which is invoked for each Pin that's added to the map:
protected override MarkerOptions CreateMarker(Pin pin)
{
var marker = new MarkerOptions();
marker.SetPosition(new LatLng(pin.Position.Latitude, pin.Position.Longitude));
marker.SetTitle(pin.Label);
marker.SetSnippet(pin.Address);
marker.SetIcon(BitmapDescriptorFactory.FromResource(Resource.Drawable.pin));
return marker;
}
If you want to display different icons, you can refer to the following code:
protected override MarkerOptions CreateMarker(Pin pin)
{
var marker = new MarkerOptions();
marker.SetPosition(new LatLng(pin.Position.Latitude, pin.Position.Longitude));
marker.SetTitle(pin.Label);
marker.SetSnippet(pin.Address);
var customPin = (Element as CustomMap).CustomPins.FirstOrDefault(p => p.Position == pin.Position);
if (customPin != null)
{
if (customPin.IconType == "corporate")
{
marker.SetIcon(BitmapDescriptorFactory.FromResource(Resource.Drawable.corporate));
}
else if (customPin.IconType == "pickup")
{
marker.SetIcon(BitmapDescriptorFactory.FromResource(Resource.Drawable.bus));
}
}
return marker;
}
For more, check:Customizing the Marker.

Exporting UltraExpandableGroupBox default expansion indicator

I am using a UltraExpandableGroupBox in my WinForms application. And I am using the Office2003 style with it. However, I would like to reverse the Expanded and Collapsed Indicator images used. I tried to export the images from the .isl file, but these images don't seems to be among the images exported. How do I access these images?
When the ViewStyle property for the UltraExpandableGroupBox control is set to the GroupBoxViewStyle.Office2003 the Expanded/Collapsed indicator uses an embedded bitmap.
Code below demonstrates how this bitmap can be obtained from the assembly on the runtime and can be used to reverse the current Expanded/Collapsed indicators:
private void ReverseImage_Click(object sender, EventArgs e)
{
var imageName = "GroupBox.ExpansionIndicator_Chevron.bmp";
System.IO.Stream stream = typeof(UltraExpandableGroupBox).Module.Assembly.GetManifestResourceStream(typeof(UltraExpandableGroupBox), imageName);
if (stream != null)
{
// The source bitmap has 7x10px size.
var image = Bitmap.FromStream(stream);
// Converting the image to 16x16 pixels
ultraExpandableGroupBox1.ExpansionIndicatorExpanded = ResizeImage(image, 16, 16);
// Rotation
using (var bmp = new Bitmap(image))
{
bmp.RotateFlip(RotateFlipType.Rotate180FlipNone);
image = bmp.Clone() as Image;
// Exporting bitmap to a file
bmp.Save(#".\" + imageName, ImageFormat.Bmp);
}
ultraExpandableGroupBox1.ExpansionIndicatorCollapsed = ResizeImage(image, 16, 16);
}
}
public static Image ResizeImage(Image image, int new_height, int new_width)
{
var dest = new Bitmap(new_width, new_height);
var g = Graphics.FromImage(dest);
g.InterpolationMode = InterpolationMode.High;
g.DrawImage(image, (dest.Width - image.Width)/2, (dest.Height-image.Height)/2);
return dest;
}
Exported to a file the Expanded/Collapsed indicator bitmap looks like on the picture below:
You can achieve this with simple DrawFilter. Set to your UltraExpandableGroupBox DraFilter property like this:
this.myUltraExpandableGroupBox.DrawFilter = new MyDrawFilter(expandedIndicator, collapsedInidcator);
Then create a new class named MyDrawFilter and let it inherit IUIElementDrawFilter. Your draw filter class may look like this:
public class MyDrawFilter : IUIElementDrawFilter
{
Image expandedIndicator;
Image collapsedIndicator;
public MyDrawFilter(Image expandedIndicator, Image collapsedInidcator)
{
this.expandedIndicator = expandedIndicator;
this.collapsedIndicator = collapsedInidcator;
}
public bool DrawElement(DrawPhase drawPhase, ref UIElementDrawParams drawParams)
{
if (drawParams.Element is GroupBoxExpansionIndicatorUIElement)
{
// if groupbox is expanded change the image with one provided in the constructor
// as expandedIndicator
if ((drawParams.Element.Control as UltraExpandableGroupBox).Expanded)
{
(drawParams.Element.ChildElements[0] as ImageUIElement).Image = this.expandedIndicator;
}
// else gropbox is collapsed change the image with one provided in the constructor
// as collapsedIndicator
else
{
(drawParams.Element.ChildElements[0] as ImageUIElement).Image = this.collapsedIndicator;
}
}
return false;
}
public DrawPhase GetPhasesToFilter(ref UIElementDrawParams drawParams)
{
// filter when GroupBoxExpansionIndicatorUIElement should be drawn. This element has
// one child UIElement of ImageUIElement type. This UIElement holds the expansion
// indicator image.
if (drawParams.Element is GroupBoxExpansionIndicatorUIElement)
{
// we return BeforeDrawChildeElements in order to be able to change the image
return DrawPhase.BeforeDrawChildElements;
}
return DrawPhase.None;
}
}

WIA: setting dinamic page size

I'm developing a WPF application to scan different documents with a scanner. The size of the documents won't be the same, can be variable.
I have my code working without scanner dialogs, and I would like the user not to have to preview the image and then scanning it to get the real size (resulting in two scans).
The problem is that I try to set page-size to auto before scanning
SetWIAProperty(item.Properties, "3097", 100);
but I get HRESULT: 0x80210067 System.Runtime.InteropServices.COMException.
I've googled to this and seens that my scanner is not supporting this property.
So, is there any way of achieving this? I need the resulting scanned image to be only the document, not all the scanner area (which I'm obtaning right now).
In case I couldn't tell the scanner to scan only the document, I've thought also in cropping the resulting image to obtain only the document I need, but don't know how to do this right now.
Here is my code:
DeviceManager deviceManager = new DeviceManager();
Device scanner = null;
foreach (DeviceInfo deviceInfo in deviceManager.DeviceInfos)
{
if (deviceInfo.DeviceID == scannerId)
{
scanner = deviceInfo.Connect();
break;
}
}
if (scanner == null)
{
throw new Exception("Scanner not found");
}
Item item = scanner.Items[1] as Item;
int dpi = 300;
SetWIAProperty(item.Properties, "6146", 1); // 1 Color
SetWIAProperty(item.Properties, "6147", dpi); // dpis
SetWIAProperty(item.Properties, "6148", dpi); // dpis
// This line throws the exception
//SetWIAProperty(item.Properties, "3097", 100); // page size 0=A4, 1=letter, 2=custom, 100=auto
try
{
ICommonDialog wiaCommonDialog = new CommonDialog();
ImageFile scannedImage = (ImageFile)wiaCommonDialog.ShowTransfer(item, FormatID.wiaFormatPNG, false);
if (scannedImage != null)
{
ImageProcess imgProcess = new ImageProcess();
object convertFilter = "Convert";
string convertFilterID = imgProcess.FilterInfos.get_Item(ref convertFilter).FilterID;
imgProcess.Filters.Add(convertFilterID, 0);
SetWIAProperty(imgProcess.Filters[imgProcess.Filters.Count].Properties, "FormatID", FormatID.wiaFormatPNG);
scannedImage = imgProcess.Apply(scannedImage);
if (System.IO.File.Exists(#"D:\temp\scanwia3.png"))
System.IO.File.Delete(#"D:\temp\scanwia3.png");
scannedImage.SaveFile(#"D:\temp\scanwia3.png");
}
scannedImage = null;
}
finally
{
item = null;
scanner = null;
}
And SetWIAProperty function:
private static void SetWIAProperty(IProperties properties, object propName, object propValue)
{
Property prop = properties.get_Item(ref propName);
prop.set_Value(ref propValue);
}
Any help would be appreciated.
Kind regards,
Jose.
Property Page Size belongs to device, not to item.
var WIA_IPS_PAGE_SIZE = "3097";
var WIA_PAGE_AUTO = 100;
SetWIAProperty(scanner.Properties, WIA_IPS_PAGE_SIZE, WIA_PAGE_AUTO);

Duplicate images printed in XPS file

First off I would like to point out that I have raised this as a bug with Microsoft but they are unwilling to fix it at this point in time. What I am looking for is a workaround or a better way of achieving what I am trying to do as our customer has deemed this a rather important issue.
The code
MainWindow.xaml
<Grid x:Name="mainGrid">
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
</Grid.RowDefinitions>
<ListBox ItemsSource="{Binding Images}">
<ListBox.ItemTemplate>
<DataTemplate>
<Image Source="{Binding}"/>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
<Button Content="Print to file" Grid.Row="1" Click="PrintToFile_Click"/>
<Button Content="Print to device" Grid.Row="2" Click="PrintToDevice_Click"/>
</Grid>
MainWindow.xaml.cs
public partial class MainWindow : Window
{
public IList<byte[]> Images { get; set; }
public MainWindow()
{
InitializeComponent();
Assembly currentAssembly = Assembly.GetExecutingAssembly();
this.Images = new List<byte[]>
{
ReadToEnd(currentAssembly.GetManifestResourceStream("PrintingInvestigation.Images.Chrysanthemum.jpg")),
ReadToEnd(currentAssembly.GetManifestResourceStream("PrintingInvestigation.Images.Desert.jpg")),
ReadToEnd(currentAssembly.GetManifestResourceStream("PrintingInvestigation.Images.Hydrangeas.jpg")),
};
this.DataContext = this;
}
public static byte[] ReadToEnd(System.IO.Stream stream)
{
long originalPosition = 0;
if (stream.CanSeek)
{
originalPosition = stream.Position;
stream.Position = 0;
}
try
{
byte[] readBuffer = new byte[4096];
int totalBytesRead = 0;
int bytesRead;
while ((bytesRead = stream.Read(readBuffer, totalBytesRead, readBuffer.Length - totalBytesRead)) > 0)
{
totalBytesRead += bytesRead;
if (totalBytesRead == readBuffer.Length)
{
int nextByte = stream.ReadByte();
if (nextByte != -1)
{
byte[] temp = new byte[readBuffer.Length * 2];
Buffer.BlockCopy(readBuffer, 0, temp, 0, readBuffer.Length);
Buffer.SetByte(temp, totalBytesRead, (byte)nextByte);
readBuffer = temp;
totalBytesRead++;
}
}
}
byte[] buffer = readBuffer;
if (readBuffer.Length != totalBytesRead)
{
buffer = new byte[totalBytesRead];
Buffer.BlockCopy(readBuffer, 0, buffer, 0, totalBytesRead);
}
return buffer;
}
finally
{
if (stream.CanSeek)
{
stream.Position = originalPosition;
}
}
}
private void PrintToDevice_Click(object sender, RoutedEventArgs e)
{
PrintDialog dialog = new PrintDialog();
if (dialog.ShowDialog() == true)
{
Thickness pageMargins;
if (dialog.PrintTicket.PageBorderless.HasValue == true)
{
if (dialog.PrintTicket.PageBorderless.Value == PageBorderless.Borderless)
{
pageMargins = new Thickness(0, 0, 0, 0);
}
else
{
pageMargins = new Thickness(20, 20, 20, 20);
}
}
else
{
pageMargins = new Thickness(20, 20, 20, 20);
}
int dpiX = 300;
int dpiY = 300;
if (dialog.PrintTicket.PageResolution != null &&
dialog.PrintTicket.PageResolution.X.HasValue &&
dialog.PrintTicket.PageResolution.Y.HasValue)
{
dpiX = dialog.PrintTicket.PageResolution.X.Value;
dpiY = dialog.PrintTicket.PageResolution.Y.Value;
}
else
{
dialog.PrintTicket.PageResolution = new PageResolution(dpiX, dpiY);
}
VisualDocumentPaginator paginator = new VisualDocumentPaginator(this.mainGrid, this.mainGrid.ActualWidth);
paginator.PageSize = new Size(dialog.PrintableAreaWidth, dialog.PrintableAreaHeight);
dialog.PrintDocument(paginator, "My first print");
GC.Collect();
}
}
private void PrintToFile_Click(object sender, RoutedEventArgs e)
{
string filePath = this.PrintToFile(null, this.mainGrid, "My first print", this.mainGrid.ActualHeight, this.mainGrid.ActualWidth);
Process.Start(filePath);
}
public string PrintToFile(Visual titleVisual, Visual contentVisual, string title, double bottomMost, double rightMost)
{
string printedFilePath = System.IO.Path.Combine(System.IO.Path.GetTempPath(), string.Format(CultureInfo.InvariantCulture, "{0}.xps", title));
XpsDocument printedDocument = new XpsDocument(printedFilePath, FileAccess.Write, System.IO.Packaging.CompressionOption.SuperFast);
VisualDocumentPaginator paginator = new VisualDocumentPaginator(contentVisual as FrameworkElement, rightMost);
paginator.PageSize = new Size(793.7, 1122.5);
XpsDocumentWriter writer = XpsDocument.CreateXpsDocumentWriter(printedDocument);
writer.Write(paginator, new PrintTicket
{
Collation = Collation.Collated,
CopyCount = 1,
DeviceFontSubstitution = DeviceFontSubstitution.On,
Duplexing = Duplexing.OneSided,
InputBin = InputBin.AutoSelect,
OutputColor = OutputColor.Color,
OutputQuality = OutputQuality.High,
PageMediaSize = new PageMediaSize(PageMediaSizeName.ISOA4),
PageOrientation = PageOrientation.Portrait,
PageResolution = new PageResolution(PageQualitativeResolution.High),
PagesPerSheet = 1,
TrueTypeFontMode = TrueTypeFontMode.Automatic
});
printedDocument.Close();
return printedFilePath;
}
}
VisualDocumentPaginator.cs
public class VisualDocumentPaginator : DocumentPaginator
{
#region Fields
private double desiredWidth;
private FrameworkElement element;
#endregion
#region Properties
public int Columns
{
get
{
return 1;// (int)Math.Ceiling(Element.ActualWidth / PageSize.Width);
}
}
public int Rows
{
get
{
return (int)Math.Ceiling(element.ActualHeight / PageSize.Height);
}
}
#endregion
#region Constructors
public VisualDocumentPaginator(FrameworkElement element, double desiredWidth)
{
this.desiredWidth = desiredWidth;
this.element = element;
}
#endregion
#region DocumentPaginator Members
public override DocumentPage GetPage(int pageNumber)
{
TransformGroup transforms = new TransformGroup();
double scaleRatio = this.PageSize.Width / this.desiredWidth;
int row = (pageNumber / Columns);
double pageHeight = -PageSize.Height * row / scaleRatio;
double pageWidth = -PageSize.Width * (pageNumber % Columns);
transforms.Children.Add(new TranslateTransform(pageWidth, pageHeight));
// Make sure the control is stretched to fit the page size.
if (scaleRatio != double.NaN)
{
ScaleTransform st = new ScaleTransform(scaleRatio, scaleRatio);
transforms.Children.Add(st);
}
element.RenderTransform = transforms;
Size elementSize = new Size(this.desiredWidth, element.ActualHeight);
element.Measure(elementSize);
element.Arrange(new Rect(new Point(0, 0), elementSize));
var page = new DocumentPage(element, this.PageSize, new Rect(), new Rect());
element.RenderTransform = null;
return page;
}
public override bool IsPageCountValid
{
get { return true; }
}
public override int PageCount
{
get
{
return Columns * Rows;
}
}
public override Size PageSize { set; get; }
public override IDocumentPaginatorSource Source
{
get { return null; }
}
#endregion
}
Apologies for posting all the code but it covers all the areas in which I am seeing the issue. If it helps here is the Microsoft bug report which has a sample project attached where the issue can be reproduced.
The problem
The issue is only seen when writing to an XPS file where only the first image is printed 3 times, if the "Print to device" button is clicked then the correct images are printed.
The reason why I am binding to a byte[] is because I am persisting my images in a local SQL CE database. We store them in a DB because they are only small ~2KB each plus we allow users to import their own Icons into the system to use and we wanted a mechanism to guarantee that they wouldn't be accidentally deleted.
NOTE
I have noticed that if I do not bind to the byte[] as mentioned above then I do not see the issue. Given the fact that the system currently works off the approach of storing the images in a DB I would prefer to stick with it if there is workaround however I am not entirely against replacing the storage mechanism for these images.
I have experienced a similar issue where the first image was duplicated and replaced all other images. In my case, printing to a device, to a XPS document or PDF document did not matter, the issue was still there.
Analysis
I have used a .NET assembly decompiler to figure out how the System.Windows.Xps.XpsDocumentWriter class deals with images to find out if the issue was in my code or in the framework's code. I discovered that the framework uses dictionnairies to import resources such as images into the document. Even if images are imported only once in the XPS document, the document is allowed to reference them many times.
In my case, I was able to figure out that the issue was located in the System.Windows.Xps.Serialization.ImageSourceTypeConverter.GetBitmapSourceFromImageTable method. When the image is built from a System.Windows.Media.Imaging.BitmapFrame, the converter will look for the resource in one of its dictionary using a key. In this case, the key correspond to the hash code of the string returned by the BitmapFrame.Decoder.ToString() method. Unfortunately, since my images are built from byte arrays instead of an URI, the decoder's ToString method returns "image". Since that string will always generate the same hash code no matter the image, the ImageSourceTypeConverter will consider that all images are already added to the XPS document and will return the Uri of the first and only image to be use. This explains why the first image is duplicated and is replacing all other images.
Attempt
My first attempt to workaround the issue was to override the System.Windows.Media.Imaging.BitmapDecoder.ToString() method. In order to do so, I tried to wrap the BitmapFrame and BitmapDecoder into my own BitmapFrame and BitmapDecoder. Unfortunately, the BitmapDecoder class contains an internal abstract method I cannot defined. Since I could not create my own BitmapDecoder, I could not implement that workaround.
Workaround
As mentionned previously, the System.Windows.Xps.Serialization.ImageSourceTypeConverter.GetBitmapSourceFromImageTable method will look for an hash code in a dictionary when the BitmapSource is a BitmapFrame. When it is not a BitmapFrame, it will instead generate a CRC value based on the image binary data and look for it in another dictionary.
In my case, I decided to wrap the BitmapFrame that were generated from byte arrays by the System.Windows.Media.ImageSourceConverter into another type of BitmapSource such as System.Windows.Media.Imaging.CachedBitmap. Since I did not really wanted cached bitmap, I created the CachedBitmap will the following options:
var imageSource = new CachedBitmap( bitmapFrame, BitmapCreateOptions.None, BitmapCacheOption.None );
With these options, the CachedBitmap is mostly a simple BitmapSource wrapper. In my case, this workaround solved my issue.
I built a custom printing solution for a document management system built on WPF. I started using the System.Printing namespace but found endless bugs in .NET that Microsoft had not resolved in a long time. With no possible workarounds I ended up using the more mature System.Drawing.Printing namespace built for Windows Forms, with which I found no issues.
It would probably take you some time to rewrite your code to System.Drawing.Printing, but you are far less likely to hit a brick wall somewhere along the way.

Determine if two images are identical

Is there any way to determine if two images are identical?
I want to change an image every time my timer ticks (animation).
But, I need to see which image is displaying, so is there any way to compare 2 images
to do what I want?
if (myImage.Flags == (Image.FromFile(#"Images/Enemy.png").Flags))
{
myImage = Image.FromFile(#"Images/Enemy2.png");
}
else
{
myImage = Image.FromFile(#"Images/Enemy.png");
}
Don't compare the images, just maintain the index of the current image in a variable.
Here's an example that works for any number of images:
private int _currentImageIndex;
private string[] _imagePaths =
{
"Images/Enemy.png",
"Images/Enemy2.png",
"Images/Enemy3.png",
};
...
void NextImage()
{
// Dispose the current image
Image img = pictureBox1.Image;
pictureBox1.Image = null;
if (img != null)
img.Dispose();
// Show the next image
_currentImageIndex = (_currentImageIndex + 1) % _imagePaths.Length;
string path = _imagePaths[_currentImageIndex];
pictureBox1.Image = Image.FromFile(path);
}
I'd try to compare ImageLocation. Although it doesn't work if you have your pictures as resources.
if (PictureBox1.ImageLocation == PictureBox2.ImageLocation)
{
}
See my question:
Dynamically changing image in a picturebox
Here goes simple answer.
In case of just 2 images, use flag
// field, true if enemy2.png is loaded
bool _image2;
// somewhere
if(_image2)
{
myImage = Image.FromFile(#"Images/Enemy.png");
_image2 = false;
}
else
{
myImage = Image.FromFile(#"Images/Enemy2.png");
_image2 = true;
}

Categories