How to check if two PictureBox have the same image? - c#

var img1 = (pictureBox1.Image = Properties.Resources.dynamite);
var img2 = (pictureBox2.Image = Properties.Resources.apple);
if (img1 != img2)
{
MessageBox.Show("ok");
pictureBox1.Image = Properties.Resources.empty;
}
else
{
MessageBox.Show("no");
Game_Over end = new Game_Over();
end.Show();
}
I want to create a simple game. If i hit a fruit the fruit picker is replace whit a empty picker and if you hit a dynamite to get game over

Convert the images into byte arrays and then do the comparison of byte arrays.
Bytearray1.SequenceEqual( bytearray2 ) can be true or false.

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.

How to use a property two times for an image?

I'm trying to add noise to my image and show it in a pixturebox,then blur it and show it in another picturebox too. But i see two blurred image on my pictureboxes. How can i show both of them?
Note: I don't want create new Bitmap.
Filtreler f1 = new Filtreler();
Bitmap Orj = new Bitmap(pBox_SOURCE.Image);
f1.Imge = Orj;
if (SablonBoyutu % 2 == 1)
{
f1.addnoise(f1.Imge);
pictureBoxNoisyImg.Image = f1.Imge;
f1.meanfilter(SablonBoyutu, f1.Imge);
pBox_PROCESSED.Image = f1.Imge;
}
class Filtreler
{
private Bitmap resim;
public Bitmap Imge
{
get { return resim; }
set { resim = value; }
}
.... (my filters)
}
I think you need one more copy (img2) of your image
f1.addnoise(f1.Imge);
pictureBoxNoisyImg.Image = f1.Imge;
var img2 = new Bitmap(pictureBoxNoisyImg.Image);
f1.meanfilter(SablonBoyutu, img2);
pBox_PROCESSED.Image = img2;
Or
f1.addnoise(f1.Imge);
pictureBoxNoisyImg.Image = new Bitmap(f1.Imge);
f1.meanfilter(SablonBoyutu, f1.Imge);
pBox_PROCESSED.Image = f1.Imge;
Edit
To dispose old images you can do
f1.addnoise(f1.Imge);
if(pictureBoxNoisyImg.Image != null)
{
pictureBoxNoisyImg.Image.Dispose();
pictureBoxNoisyImg.Image = null;
}
pictureBoxNoisyImg.Image = new Bitmap(f1.Imge);
f1.meanfilter(SablonBoyutu, f1.Imge);
if(pBox_PROCESSED.Image != null)
{
pBox_PROCESSED.Image.Dispose();
pBox_PROCESSED.Image = null;
}
pBox_PROCESSED.Image = f1.Imge;
There is an alternative method which called Cloning (image.Clone();) instead of using new Bitmap Instance. Maybe it will help to you.
What's the difference between Bitmap.Clone() and new Bitmap(Bitmap)?

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

Image Slider in C#?

I want to create a simple image slideshow, when the timer switch, it will switch to the next index of the picturebox (and will loop) but with a fade effect. How can it be done in C#?
Current Code doesn't switch images? And also - how can I create the fade ffect?
I created a simple timer with 5,000ms interval, enabled it on start.
private void timerImage_Tick(object sender, EventArgs e)
{
if (pictureBox1.Image.Equals(InnovationX.Properties.Resources._1))
{
pictureBox1.Image = InnovationX.Properties.Resources._2;
}
else if (pictureBox1.Image.Equals(InnovationX.Properties.Resources._2))
{
pictureBox1.Image = InnovationX.Properties.Resources._3;
}
else
{
pictureBox1.Image = InnovationX.Properties.Resources._1;
}
}
You can't compare Bitmap loaded from resource in this manner. Every time you get image from resource (in your case using property InnovationX.Properties.Resources._1) you will get new instance of Bitmap class. Comparing two different instances of Bitmap classes will always result in false, even if they contains same image.
Bitmap a = InnovationX.Properties.Resources._1; // create new bitmap with image 1
Bitmap b = InnovationX.Properties.Resources._1; // create another new bitmap with image 1
bool areSameInstance = a == b; // will be false
If you load you images from resources to member variables (e.g. in Load event).
// load images when you create a form
private Bitmap image1 = InnovationX.Properties.Resources._1;
private Bitmap image2 = InnovationX.Properties.Resources._2;
private Bitmap image3 = InnovationX.Properties.Resources._3;
// assing and compare loaded images
private void timerImage_Tick(object sender, EventArgs e)
{
if (pictureBox1.Image == image1)
{
pictureBox1.Image = image2;
}
else if (pictureBox1.Image == image2)
{
pictureBox1.Image = image3;
}
else
{
pictureBox1.Image = image1;
}
}
And after that, rewrite that code using array :)
Image[] images = new {
InnovationX.Properties.Resources._1,
InnovationX.Properties.Resources._2,
InnovationX.Properties.Resources._3
};

Drawing Transparent Images

I'm writing a CSS sprite engine in C#, however I'm having a few issues. I create the master image, set all the properties to that then iterate the sprites and draw those to the master image. However when I come to save the master image it only appears to be just the empty master image with transparent background and none of the sprites. I'm very confused at where I'm going wrong.
The code I'm using is:
// Work out the width/height required
int max_width = 0;
int max_height = 0;
foreach(SpriteInformation sprite in sprites) {
if (max_width < (sprite.Left + greatest_width)) max_width = sprite.Left + greatest_width;
if (max_height < (sprite.Top + greatest_height)) max_height = sprite.Top + greatest_height;
}
// Create new master bitmap
Bitmap bitmap = new Bitmap(max_width,max_height,PixelFormat.Format32bppArgb);
Graphics graphics = Graphics.FromImage(bitmap);
// Set background color
SolidBrush brush;
if (cbxBackground.Checked) {
if (txtColor.Text == "") {
brush = new SolidBrush(Color.Black);
} else {
brush = new SolidBrush(pnlColor.BackColor);
}
} else {
if (txtColor.Text == "") {
brush = new SolidBrush(Color.White);
} else {
brush = new SolidBrush(pnlColor.BackColor);
}
}
//graphics.FillRectangle(brush,0,0,bitmap.Width,bitmap.Height);
bitmap.MakeTransparent(brush.Color);
graphics.Clear(brush.Color);
// Copy images into place
ImageAttributes attr = new ImageAttributes();
//attr.SetColorKey(brush.Color,brush.Color);
foreach(SpriteInformation sprite in sprites) {
Rectangle source = new Rectangle(0,0,sprite.Width,sprite.Height);
Rectangle dest = new Rectangle(sprite.Left,sprite.Top,sprite.Width,sprite.Height);
graphics.DrawImage(sprite.Sprite,dest,0,0,sprite.Width,sprite.Height,GraphicsUnit.Pixel,attr);
}
// Save image
string format = ddlFormat.Items[ddlFormat.SelectedIndex].ToString();
if (format == "PNG") {
dlgSave.Filter = "PNG Images|*.png|All Files|*.*";
dlgSave.DefaultExt = ",png";
if (dlgSave.ShowDialog() == DialogResult.OK) {
bitmap.Save(dlgSave.FileName,ImageFormat.Png);
}
} else if (format == "JPEG") {
} else {
}
What are sprite.Left and Top? If they aren't 0 that may be a problem. I think you have dest and source the wrong way round?
http://msdn.microsoft.com/en-us/library/ms142045.aspx
Try a simpler DrawImage variant if you haven't already.
e.g. DrawImage(sprite.Sprite,0,0)
You draw to "graphics", but then then you save "bitmap"? I'm not sure if that graphics internally works with your original "bitmap" object...

Categories