I just wrote thsi code to have an access to images
private Bitmap[] hi = { HangmanUrdu.Properties.Resources._4, HangmanUrdu.Properties.Resources._5, HangmanUrdu.Properties.Resources._6, HangmanUrdu.Properties.Resources._7, HangmanUrdu.Properties.Resources._8, HangmanUrdu.Properties.Resources._9, HangmanUrdu.Properties.Resources._10 };
but when i want to increment the index and get these images in my picture box
// wg is just a counter;
pictureBox1.Image = hi { wg}; i
t throws me an error saying
cannot implicitly convert Bitmap to images
I also tried to change my array from bitmap to image but then it shows me error that cannot convert Images to Images.
Create a List<Bitmap> - as a Field, here - or any other type that fits the design (a class property, for example).
Fill the List<Bitmap> in a Form's constructor with the Bitmap objects needed in that context, creating a new Bitmap from the resource object:
private List<Bitmap> hi = null;
public Form1()
{
InitializeComponent();
this.hi = new List<Bitmap>()
{
new Bitmap(Properties.Resources._4),
new Bitmap(Properties.Resources._5)
};
}
The assign a Bitmap to a control's Image property when you need to:
pictureBox1.Image = hi[1];
You could also build a specialized class that hold these references, so you can access them with different naming conventions.
For example:
private List<BitmapResource> BitmapResources = null;
public Form1()
{
InitializeComponent();
this.BitmapResources = new List<BitmapResource>()
{
new BitmapResource(new Bitmap(Properties.Resources._4), "Logo"),
new BitmapResource(new Bitmap(Properties.Resources._5), "Watermark")
};
}
internal class BitmapResource
{
public BitmapResource(Bitmap bitmap, string imageName)
{
this.Image = bitmap;
this.Name = imageName;
}
public Bitmap Image { get; private set; }
public string Name { get; private set; }
}
Then, when needed:
By index:
pictureBox1.Image = BitmapResources[0].Image;
By name (simplified):
pictureBox1.Image = BitmapResources.FirstOrDefault(res => res.Name == "Logo").Image;
Related
I am creating a BlackJack game and I'm currently having a problem displaying the card image needed on my list.
I have added all 52 card to my resource file and I can't seem to have them displayed in a PictureBox.
Am I going about the right way?
My Card class:
internal class Card
{
public int Value { get; set; }
public string Name { get; set; }
public string Image { get; set; }
public Card(int value, string name, string image)
{
Value = value;
Name = name;
Image = image;
}
}
Main Form:
public partial class Form1 : Form
{
static List<Card> myListOfCards = new List<Card>();
static List<Card> dealersHand = new List<Card>();
static List<Card> playersHand = new List<Card>();
private void startButton_Click(object sender, EventArgs e)
{
//Clubs
myListOfCards.Add(new Card(2, "Two of Clubs", "Resources._2C.png"));
}
}
I've spotted a potential issue. Your code uses "Resources._2C.png" as a literal, and the Card class deals with it as a string. One way or another an Image must be retrieved from the resources of the Assembly and I don't see any code that does that.
Try this change:
class Card
{
// METHOD 1
// CTor with Image
public Card(int value, string name, Image image)
{
Value = value;
Name = name;
Image = image;
}
// METHOD 2
// CTor with string
// The `BuildAction` property for the image files must
// be set to `EmbeddedResource` for this version to work.
public Card(int value, string name, string resource)
{
Value = value;
Name = name;
Image = Image.FromStream(
typeof(Card)
.Assembly
.GetManifestResourceStream(resource));
}
public int Value { get; }
public string Name { get; }
// Try making this an Image
public Image Image { get; }
}
In the MainForm:
The image can either be read from the Resource file by removing the quotes and the extension:
// METHOD 1
private void buttonCard1_Click(object sender, EventArgs e)
{
var card = new Card(1, "AceOfDiamonds", Resources.AceOfDiamonds);
pictureBox1.Image = card.Image;
}
OR if the string is used, it must be fully qualified:
// METHOD 2
private void buttonCard2_Click(object sender, EventArgs e)
{
// Get full names of available resources
Debug.WriteLine(
string.Join(
Environment.NewLine,
typeof(MainForm).Assembly.GetManifestResourceNames()));
var card = new Card(2, "EightOfSpades", "resources.Images.EightOfSpades.png");
pictureBox1.Image = card.Image;
}
Gets this in the PictureBox:
FYI: Here are the available embedded resources listed by the Debug.WriteLine:
I would like to browse an image from form window. Also I created a class and created some filters. I can read this image from form.
My goal is declare it in my class. And use this image in everywhere. But I don't know how can I do this.
private void btn_BROWSE_Click(object sender, EventArgs e)
{
OpenFileDialog imge = new OpenFileDialog();
imge.Filter = "Extensions |*.bmp;*.jpg;*.jpeg;*.png;*.tif;*.tiff|"
+ "BMP|*.bmp|GIF|*.gif|JPG|*.jpg;*.jpeg|PNG|*.png|TIFF|*.tif;*.tiff|"
+ "Zip Files|*.zip;*.rar";
imge.ShowDialog();
string imgepath = imge.FileName;
pBox_SOURCE.ImageLocation = imgepath;//i'm browsing an image
}
private void sliderKernel_MouseUp(object sender, MouseEventArgs e)
{
Bitmap OriginalImage = new Bitmap(pBox_SOURCE.Image);
}
class Filters
{
// (i would like to initialize my image in here not in form :) )
}
I would define an abstract class Filter and implement every filter as an heir of that class.
public abstract class Filter
{
public Bitmap Image { get; set; }
public abstract void Apply();
}
An implementation would be:
public class SliderKernel : Filter
{
public overrides void Apply()
{
//manipulates the Image property
}
}
If you want to use that image everywhere you should declare it as a static member of a class:
public static class ImageContainer
{
public static Bitmap Image { get; set; }
}
You can use all this in your form code like this:
private void btn_BROWSE_Click(object sender, EventArgs e)
{
OpenFileDialog imge = new OpenFileDialog();
imge.Filter = "Extensions |*.bmp;*.jpg;*.jpeg;*.png;*.tif;*.tiff|"
+ "BMP|*.bmp|GIF|*.gif|JPG|*.jpg;*.jpeg|PNG|*.png|TIFF|*.tif;*.tiff|"
+ "Zip Files|*.zip;*.rar";
imge.ShowDialog();
string imgepath = imge.FileName;
pBox_SOURCE.ImageLocation = imgepath;//i'm browsing an image
//save the image to the container
ImageContainer.Image = new Bitmap(pBox_SOURCE.Image);
}
private void sliderKernel_MouseUp(object sender, MouseEventArgs e)
{
Filter filter = new SliderKernel () { Image = ImageContainer.Image };
filter.Apply();
}
I think you should turn the image into a byte array
using the following code and store it in a static class
public byte[] ImageToByteArray(System.Drawing.Image imageIn)
{
using (var ms = new MemoryStream())
{
imageIn.Save(ms,imageIn.RawFormat);
return ms.ToArray();
}
}
https://www.codeproject.com/Articles/15460/C-Image-to-Byte-Array-and-Byte-Array-to-Image-Conv
And use this code to turn into a graphic to display in pictureBox
public Image byteArrayToImage(byte[] byteArrayIn)
{
MemoryStream ms = new MemoryStream(byteArrayIn);
Image returnImage = Image.FromStream(ms);
return returnImage;
}
So I am making some achievement pop ups for a lame game and so I made a custom messagebox form and I have been successful in setting the popups picturebox image with local images but I need help using embedded resources as images.
So far Ive used constructors to set the images and string but I can't use them for embedded images.
Parent Form:
MessageForm MsgFrm = new MessageForm
{
AchievementString = "L33t H4x0r - Reach 1337 score.",
PictureString = "C:\\Users\\Resources\\H4x0r_50x50.jpg"
};
MsgFrm.Show();
Child Form:
public string Achstring { get; set; }
public string Picstring { get; set; }
private void MessageForm_Load(object sender, EventArgs e)
{
achievement_lbl.Text = AchievementString;
achievement_pic.Image = Image.FromFile(PictureString);
}
Using the code above I can only use local images and my goal is to use images embedded in resources but to pass them as an arg of sorts as above.
You should either pass the Image object to a constructor or declare an Image property to set.
public MessageForm(Image img)
{
InitializeComponent();
achievement_pic.Image = img;
}
Or
Parent form
MessageForm MsgFrm = new MessageForm
{
AchievementString = "L33t H4x0r - Reach 1337 score.",
PictureImg = embeddedPicture
};
MsgFrm.Show();
Child form
public string Achstring { get; set; }
public Image PicImage { get; set; }
private void MessageForm_Load(object sender, EventArgs e)
{
achievement_lbl.Text = AchievementString;
achievement_pic.Image = PicImage
}
If you need more control in the parent form, you could make the control public or create a public property for the image.
public Control PicControl => achievement_pic;
I have the following class:
class Sapo
{
private Image imgSapo;
public int IdSapo { get; }
public Sapo(int id)
{
imgSapo = new Image();
IdSapo = id;
}
public Image show
{
get
{
imgSapo.Source = new BitmapImage(new Uri("pack://application:,,,/Imagens/sapo.png", UriKind.Absolute));
imgSapo.Width = 56;
imgSapo.Height = 56;
return imgSapo;
}
}
}
And I have a method where I create a thread passing an instance of each object of class Sapo:
public void CriarSapos()
{
Thread th;
int sapos = int.Parse(txt_sapos.Text);
Sapo[] arraySapos = new Sapo[sapos];
for (int i = 0; i < sapos; i++)
{
th = new Thread(new ParameterizedThreadStart(ThreadImageSapo));
th.SetApartmentState(ApartmentState.STA);
th.IsBackground = true;
arraySapos[i] = new Sapo(th.ManagedThreadId);
th.Start(arraySapos[i]);
}
}
The method responsible for inserting the images on the canvas:
public void ThreadImageSapo(object obj)
{
Dispatcher.Invoke(() =>
{
Sapo _sapo = (Sapo)obj;
double max_x = _canvas.ActualWidth - _sapo.show.Width;
double max_y = _canvas.ActualHeight - _sapo.show.Height;
Canvas.SetLeft(_sapo.show, rnd.NextDouble() * max_x);
Canvas.SetTop(_sapo.show, rnd.NextDouble() * max_y);
_canvas.Children.Add(_sapo.show);
});
}
My objective is that I want to check the collision of images in the canvas and destroy the thread in which the object of that image consists
My question is: How can I get the respective object of the canvas image?
First of all, you should generally not create UI elements in code behind, especially in a non-UI thread. Change you Sapo class so that it hold a BitmapImage in a property, instead of an Image control. Also make sure to call Freeze() on the BitmapImage to make it cross-thread accessible.
public class Sapo
{
public int IdSapo { get; private set; }
public double Width { get; private set; }
public double Height { get; private set; }
public BitmapImage Image { get; private set; }
public Sapo(int id)
{
IdSapo = id;
Width = 56;
Height = 56;
Image = new BitmapImage(new Uri("pack://application:,,,/Imagens/sapo.png"));
Image.Freeze();
}
}
Now when you add the image to a Canvas, create an Image control and assign the BitmapImage like this:
Dispatcher.Invoke(() =>
{
var sapo = (Sapo)obj;
var image = new Image
{
Source = sapo.Image,
Width = sapo.Width,
Height = sapo.Height
};
double maxX = _canvas.ActualWidth - image.Width;
double maxY = _canvas.ActualHeight - image.Height;
Canvas.SetLeft(image, rnd.NextDouble() * maxX);
Canvas.SetTop(image, rnd.NextDouble() * maxY);
_canvas.Children.Add(image);
});
This still creates an Image control in code behind, but in the UI thread. A better solution might be to use an ItemsControl with a Canvas as ItemsPanel.
Morning all,
I've created a custom control with an image property. That image property is a get/set to a private Image variable.
Can anyone tell me how I enable that get/set to clear the property from the designer?
I.e. if I add an image to a standard PictureBox, I can hit Del to clear the image from the PictureBox. How can I replicate this behaviour on my own custom control?
At the simplest level, DefaultValueAttribute should do the job:
private Bitmap bmp;
[DefaultValue(null)]
public Bitmap Bar {
get { return bmp; }
set { bmp = value; }
}
For more complex scenarios, you might want to try adding a Reset method; for example:
using System;
using System.Drawing;
using System.Windows.Forms;
class Foo {
private Bitmap bmp;
public Bitmap Bar {
get { return bmp; }
set { bmp = value; }
}
private void ResetBar() { bmp = null; }
private bool ShouldSerializeBar() { return bmp != null; }
}
static class Program {
[STAThread]
static void Main() {
Application.EnableVisualStyles();
Form form = new Form();
PropertyGrid grid = new PropertyGrid();
grid.Dock = DockStyle.Fill;
grid.SelectedObject = new Foo();
form.Controls.Add(grid);
Application.Run(form);
}
}