no error but cannot load image in windows form - c#

the code is here,designer window has a button and a picture box!
private void button1_Click(object sender, EventArgs e)
{
OpenFileDialog dlg = new OpenFileDialog();
dlg.Title = "Open Image";
dlg.Filter = "bmp files (*.bmp)|*.bmp";
if (dlg.ShowDialog() == DialogResult.OK)
{
PictureBox PictureBox1 = new PictureBox();
PictureBox1.Image = Image.FromFile(dlg.FileName);
/* PictureBox1.Image = new Bitmap(dlg.FileName);
// Add the new control to its parent's controls collection
this.Controls.Add(PictureBox1);
//dlg.Dispose();*/
}
}
there is no error the window opens,when i press the button it opens directory ,then selected the image ,but it is not able to load the image in the window. the image im loading is 49.6 MB ,does that create any problem.

You've commented out the part where you added the picturebox to your window, id also suggest setting some elementary width/height of the picturebox so you can be sure it shows on screen.
Does it work with a much smaller test image?

Instead of creating the picture box on the fly, put it wherever you like in the Designer and set its Visible property to False.
Assuming you will name it PictureBox1 just assign its Image whenever the button is pressed, without creating any new picture box and in addition change its Visible to true:
PictureBox1.Image = Image.FromFile(dlg.FileName);
PictureBox1.Visible = true;
With your current code, the picture box gets default position of 0,0 which means top left corner of the window.

Try to
PictureBox.Image = new Bitmap(dlg.FileName);
PictureBox.SizeMode = PictureBoxSizeMode.StretchImage;

Related

Resize an image in a button C# (not background image)

I inserted an image into a button, but it's not a background image. So, I want to resize the image's size that I want for example Height=30, Width=20 or sometime Height=50, Width=50. Some people told me that it's impossible to resize an image in a button if I inserted it as an background image it's possible.However, if I insist to resize the image it's possible? I don't believe that nobody can do it.
Is this a windows form application? Forgive me if I didn't understand the question, but you should be able to resize the image from the Properties menu if you're using a PictureBox. Right-click on the image you inserted, select properties and there should be a field for Size.
I am assuming that you want to resize the image present inside the button. You can try something like this in Designer File:
//
// ButtonName
//
this.ButtonName.AutoSize = false;
Image image = new Bitmap(customWidth,customHeight);
using (Graphics g = Graphics.FromImage(image )) {
g.DrawImage(FileLocation, 0, 0, customWidth, customHeight);
}
this.ButtonName.Image = image;
This will help in button resizing but the picture won't be clear if much increased.
Button.Resize += Button_Resize;
private void Button_Resize(object sender, EventArgs e)
{
Button button = (Button)sender;
Image resize = new Bitmap(button.Image,new Size(button.Image.Width, (button.Height - 13))); button.Image = resize;
}

How to add a picturebox above a button control

I have a picturebox1 -> Button -> picturebox2 all three are in a consecutive layer so which I want is that picturebox2 should be appear within the button when I debug the program.
My code is,
public Form1()
{
InitializeComponent();
picturebox2.parent = button;
picturebox.backcolor = color.transparent;
}
I am using .jpg for picturebox1 and a .png for picturebox2 but its not appearing. I mean the picture of picturebox2 should appear above the button.
You need to nest all 3 controls.
You also need to correct the Location of the nested controls or else they keep the original location, which are relative to their original parents, probably to the form, and not to their new parents!!
This should work better:
public Form1()
{
InitializeComponent();
button.Parent = picturebox;
picturebox2.Parent = button;
picturebox.BackColor = Color.Transparent;
button.Location = new Point(1,2); // or whatever you want!!
picturebox2.Location = new Point(3,4); // or whatever you want!!
}
You may also want to consider simply using the Image and/or the BackGroundImage properties of the Button..
Note: If you want your Button to let the bottom PictureBox shine through you need to not only set its Color but also it's FlatStyle to Flat!

How to set the background image of a panel from a resource file in C#?

I want to change the background image of a panel in a C# Windows Forms application. The image I want to set as the background is located in a resource folder in Solution Explorer. How do I use it in code?
I tried this:
panel1.BackgroundImage = Properties.Resources.Chalkboard;
But it didn't work.
I tried the same code like you did, and it works fine when I hit a button.
private void pnlBgBtn_Click(object sender, EventArgs e)
{
panel1.BackgroundImage = Properties.Resources.image;
}
The name 'image' in 'Properties.Resources.image' should be the name you gave to the image.
The right name of the image should be the name shown in your project properties under project-proje.
The properties.Resources class doesn't return every resourse as an image so you have to apply a cast to Image like this
panel1.BackgroundImage = (Image)(Properties.Resourses.Chalkboard);
You can try this out:
Bitmap bmp = new Bitmap(System.Reflection.Assembly.GetEntryAssembly().
GetManifestResourceStream("MyProject.Resources.myimage.png"));
panel1.BackgroundImage = bmp;
If you want to set the background image of a panel on page load then you have to write this code:
private void panel1_Paint(object sender, PaintEventArgs e)
{
Assembly asm = Assembly.GetExecutingAssembly();
Bitmap backgroundImage = new Bitmap(asm.GetManifestResourceStream("Image913.jpg"));
e.Graphics.DrawImage(
backgroundImage,
this.ClientRectangle,
new Rectangle(0, 0, backgroundImage.Width, backgroundImage.Height),
GraphicsUnit.Pixel);
}
If you want set the image except the panel, load use this code:
Bitmap bmp = new Bitmap(System.Reflection.Assembly.GetEntryAssembly().
GetManifestResourceStream("MyProject.Resources.photo0018.jpg.png"));
panel1.BackgroundImage = bmp;
You can create an icon resource in Properties project folder. When you opened Properties click on Resources.resx and there Add Resource->Add New Icon menu items. This will create an icon. You can also load an icon from an existing file into the resource, in this case the icon will be built in your executable. So, when your icon added as a resource it will be given some name.

How to split an image into 9 pieces and place in a canvas randomly?

I am trying to select an image and split it into 9 pieces and place randomly in a canvas. I am at the point where I have selected an image, but I am unsure of how to split the image.
I have looked at similar questions but no luck. I'm not looking for someone else to do the work, but advice on how best to do it.
private void uploadImage_Click(object sender, RoutedEventArgs e)
{
//creates (but not yet displays) a OpenFile dialog box
Microsoft.Win32.OpenFileDialog dlg = new Microsoft.Win32.OpenFileDialog();
//specifies the look of the open file dialog box
dlg.DefaultExt = ".jpg";
dlg.Filter = "Image Files|*.jpg;";
dlg.InitialDirectory = Environment.CurrentDirectory;
//shows the open file dialog box to user and awaits OK or Cancel
bool? result = dlg.ShowDialog();
//result is true if user selects an image file
if (result == true)
{
filename = dlg.FileName;
var uri = new Uri(filename);
var bitmap = new BitmapImage(uri);
Image bg = new Image();
bg.Source = new BitmapImage(uri);
}
else
return;
}
I have already answered similiar question. Either use my solution, or resort to CroppedBitmap.
How to crop image and save into ImageSource in WPF?

Clickable image grid in windows form?

If this is a dumb question, forgive me. I have a small amount of experience with C#, but not to this degree yet.
I have a series of images that I want to put into a grid with space around each image, also text beneath them and I want them to be clickable, so when they're clicked they hilite, and double click runs an event. The best example I have for this is the user interface of the program ACDSee. I've googled this for hours, and haven't come up with anything applicable. Is this difficult or simple? Can anyone give me an example, or point me in the right direction?
Cheers.
It doesn't seem to be very difficult. I would suggest the following steps:
Add a new "User Control" to your project for image thumbnails. It can contain a docked PictureBox and a Label or LinkLabel at its bottom.
For the space around each thumbnail simply play with the Padding property of the user control.
For the so called grid that is going to hold the thumbnails, use a FlowLayoutPanel, and simply add instances of the above mentioned user-control to this panel.
For visual representation of being selected, change the background color of the user-control instance to blue (for example), and back to control-face when deselected. It is recommended to implement an IsSelected property for the user-control as well.
To emulate thumbnail selection, handle the Click event of the user-control and assign the events for all thumbnail instances to a single event-handler method. Store a global reference to the already selected thumbnail, name it e.g., SelectedThumbnail initialized with null. In the event-handler body compare the sender with the global SelectedThumbnail, and update it if required. If the user-control associated with the sender is not selected (i.e., its background is not blue, or IsSelected is false) make it selected, or change its background. Otherwise change the background to its default color (e.g., control-face).
The Click event handler body looks something like this:
MyThumbnailControl ctrl = sender as MyThumbnailControl;
if(ctrl == null) return;
if(ctrl == SelectedThumbnail) return; // selected again
if(ctrl != SelectedThumbnail)
{
ctrl.IsSelected = true;
ctrl.BackColor = Color.Blue;
// it's better to set the back-color in the IsSelected property setter, not here
SelectedThumbnail.IsSelected = false;
SelectedThumbnail.BackColor = Color.Control;
SelectedThumbnail = ctrl; // important part
}
It's also recommended that all thumbnail instances that are going to be added to the so-called grid, be referenced in a separate array too. Therefore changing selection with arrow-keys would be possible with simple index calculations.
Further Notes: I assumed that the user-control that is to be created is named MyThumbnailControl, just a random name to refer to that control. When you create a new user-control, the wizard generates a class for you with your desired name (e.g., MyThumbnailControl), you can define a property inside it named IsSelected and implement its getter and setter. See this for a tutorial. After defining the user-control you can instantiate instances from its corresponding class. Also by global reference, I meant a variable at the form (or any parent control) level. To keep it simple we can add a reference of the selected thumbnail in the form that is going to hold the grid and thumbnails: MyThumbnailControl selectedThumb = null; or something like this in the body of the form.
Here is something, I just fixed you.
Create a C# project name CreateImageList and in the Form1 add the following 5 controls with their default name i.e. Panel1, PictureBox1, Label1, Button1, Button2:
How it works:
When the page load it create an imageList objects and load all .jpg images from a folder you provide
ImageList Images are set into the PictureBox control and when user clicks "Button1" the picturebox shows next image in ImageList and when user clicks "Button2" the PictureBox shows previous image from ImageList.
The Label1 shows the currentImage counter from the ImageList Arrage. If you want to write something specific, you can create an array of text and sync with your image counter.
When user click on PictureBox the a border is create to show Picture highlighted
When user Double Click on PictureBox a MessageBox appears shows DoubleClick event.
Now, you can use the following code:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
namespace CreateImageList
{
public partial class Form1 : Form
{
private int currentImage = 0;
protected Graphics myGraphics;
ImageList iPicList = new ImageList();
public Form1()
{
InitializeComponent();
DirectoryInfo dirImages = new DirectoryInfo("C:\\2012");
iPicList.ImageSize = new Size(255, 255);
iPicList.TransparentColor = Color.White;
myGraphics = Graphics.FromHwnd(panel1.Handle);
foreach (FileInfo file in dirImages.GetFiles())
{
if (file.Extension == ".jpg")
{
Image myImage = Image.FromFile(file.FullName);
iPicList.Images.Add(myImage);
}
}
if (iPicList.Images.Empty != true)
{
panel1.Refresh();
currentImage = 0;
// Draw the image in the panel.
iPicList.Draw(myGraphics, 1, 1, currentImage);
// Show the image in the PictureBox.
pictureBox1.Image = iPicList.Images[currentImage];
label1.Text = "Image #" + currentImage;
}
}
private void showImage(int imgIndex)
{
// Draw the image in the panel.
iPicList.Draw(myGraphics, 1, 1, currentImage);
// Show the image in the PictureBox.
pictureBox1.Image = iPicList.Images[currentImage];
label1.Text = "image #" + currentImage;
panel1.Refresh();
}
private void button1_Click(object sender, EventArgs e)
{
if (iPicList.Images.Count - 1 > currentImage)
{
currentImage++;
}
else
{
currentImage = 0;
}
showImage(currentImage);
}
private void button2_Click(object sender, EventArgs e)
{
if (iPicList.Images.Count - 1 >= currentImage)
{
if (currentImage == 0)
currentImage = iPicList.Images.Count-1;
else
currentImage--;
}
else
{
currentImage = iPicList.Images.Count;
}
showImage(currentImage);
}
private void pictureBox1_DoubleClick(object sender, EventArgs e)
{
MessageBox.Show("Picture Box Double clicked");
}
private void pictureBox1_Click(object sender, EventArgs e)
{
panel1.Refresh();
myGraphics.DrawRectangle(Pens.Black, 0, 0, iPicList.Images[currentImage].Width + 1, iPicList.Images[currentImage].Height + 1);
pictureBox1.Image = iPicList.Images[currentImage];
}
}
}
The changes you need are:
Change the Following folder to a place where you have lots of jpg:
DirectoryInfo dirImages = new DirectoryInfo("C:\\2012");
Also if you are dealing with other kind of images, make change here:
if (file.Extension == ".jpg") // Change it to your image type.
If you don't want to use the the buttons to go up and down, you have several other options to host PictureBox control in scrollable Panel or list or something else.

Categories