I wanted to show my pics in picturebox. but also wanted to show a preview of pics.
When user select a pic, it is shown in picbox but i have problem in resoulution.
Here is my code
private void openToolStripMenuItem_Click(object sender, EventArgs e)
{
ofd = new OpenFileDialog();
ofd.Title = "Open an Image File";
ofd.FileName = "";
ofd.Filter = "Image Files(*.jpg; *.jpeg; *.gif; *.bmp)|*.jpg; *.jpeg; *.gif; *.bmp";
if (ofd.ShowDialog() == DialogResult.OK)
{
DirectoryInfo dir = new DirectoryInfo(#"c:\pic");
foreach (FileInfo file in dir.GetFiles())
{
this.imageList1.Images.Add(Image.FromFile(file.FullName));
}
this.listView1.View = View.LargeIcon;
this.imageList1.ImageSize = new Size(40, 40);
this.listView1.LargeImageList = this.imageList1;
for (int j=0; j < this.imageList1.Images.Count; j++) {
ListViewItem item = new ListViewItem();
item.ImageIndex = j;
listView1.Items.Add(item);
ListViewItem item2 = new ListViewItem();
item2.SubItems.Add(j.ToString());
}
private void listView1_SelectedIndexChanged(object sender, EventArgs e)
{
int i = this.listView1.FocusedItem.Index;
this.PicBox1.Image = this.imageList1.Images[i];
}
On click i see only image of resolution of (40,40) becuse i have set it
this.imageList1.ImageSize = new Size(40, 40); and not orignal size.
How can I have it.
2-
I want to write also image names and index(image no) under each images.
Its it possible.
reagrsd,
I suppose, that after you have loaded an image to the imageList with resolution 40, 40, there is no way to make it higher.
You should save the original picture in another container like List<> and display the original image from the list and not from the imagelist :)
-Create a new imagelist (imagelist1)**
-Add images to your imagelist
-Create a new listview (listview1)
-Create a picturebox (picturebox1)
-Create a new button (button1)
-Create another button (button2)**
-Import images from imagelist1 to listview1
private void button1_Click(object sender, EventArgs e)
{
listView1.Scrollable = true;
listView1.View = View.LargeIcon;
imageList1.ImageSize = new Size(100, 100);
listView1.LargeImageList = imagelist1;
for (int i = 0; i < imagelist1.Images.Count; ++i)
{
string s = imagelist1.Images.Keys[i].ToString();
ListViewItem lstItem = new ListViewItem();
lstItem.ImageIndex = i;
lstItem.Text = s;
listView1.Items.Add(lstItem);
}
}
- Set the selected image into your picture box from listview
private void button2_Click(object sender, EventArgs e)
{
if (this != null && listView1.SelectedItems.Count > 0)
{
ListViewItem lvi = listView1.SelectedItems[0];
string imagekeyname = lvi.Text;
if (this.pictureBox1.Image != null)
{
this.pictureBox1.Image.Dispose();
this.pictureBox1.Image = null;
}
//set the selected image into your picturebox
this.pictureBox1.Image = imagelist1.Images[imagekeyname];
}
}
and its done.
Related
I have some pictures in a database which I retrieve them . To load these pictures, I made a "Tab Control" in Windows Form, which has a "Tab page1". when the program runs, a group box, containing a PictureBox (and some other text boxes), will be created for each picture. my pictures can be load in these picture boxes, and I will have a list of group boxes(gbList). However, I can not select these pictures during the run. Can anybody suggest a solution?
private void Form2_Load(object sender, EventArgs e)
{
tabPage1.Controls.Clear();
int x = 0, y = 0;
int j = 0;
for (int i = 0; i < output.Count - 1; i++)
{
PictureBox pic = new PictureBox();
pic.SizeMode = PictureBoxSizeMode.StretchImage;
SelectablegroupBox gb = new SelectablegroupBox();
gb.Controls.Add(pic);
gbList.Add(gb);
//to retrieve the images from the database in ProductImages class: (output is the result of a query of database)
ProductImages pI = output[i];
imgbyte = pI.Pic;
using (MemoryStream ms = new MemoryStream(imgbyte))
{
Image img = Image.FromStream(ms);
pic.Image = img;
}
//to add the group box list o the tabpage:
tabPage1.Controls.Add(gbList[j]);
gbList[j].Location = new Point(x, y);
y += gbList[i].Height;
j++;
}
here is my problem. I want the user to be able to select the images (Then I want to save these selected Items). But the "result" is always empty:
var result = from s in gbList
where s.Focused ==true
select s;
foreach (var s in result)
{ //save the selected images}
As I learned from another post, I defined SelectablegroupBox" as:
class SelectablegroupBox : GroupBox
{
public SelectablegroupBox()
{
this.SetStyle(ControlStyles.Selectable, true);
this.TabStop = true;
}
protected override void OnEnter(EventArgs e)
{
this.Focus();
this.Invalidate();
base.OnEnter(e);
}
protected override void OnPaint(PaintEventArgs pe)
{
base.OnPaint(pe);
if (this.Focused)
{
var rc = this.ClientRectangle;
rc.Inflate(-2, -2);
ControlPaint.DrawFocusRectangle(pe.Graphics, rc);
}
}
}
thanks in advance
Your class SelectableGroupBox is not suitable to let the user select one or more images. There can be at most one focused control in your app - this will be probably a button on your form which the user clicks to save the selected images.
One simple solution would be to use CheckBox controls with the Appearance property set to Button. Also, you don't have to layout the images manually, let a FlowLayoutPanel do the job.
First, add a FlowLayoutPanel named flowLayoutPanel to your tabPage2 and set the following Properties:
flowLayoutPanel.AutoScroll = true;
flowLayoutPanel.Dock = System.Windows.Forms.DockStyle.Fill;
Then change the appropriate code in Form2 to:
private const int imageWidth = 128;
private const int imageHeight = 128;
protected override void OnLoad(EventArgs e)
{
base.OnLoad(e);
for (int i = 0; i < output.Count; i++)
{
CheckBox cb = new CheckBox();
cb.Appearance = Appearance.Button;
cb.Size = new Size(imageWidth, imageHeight);
cb.BackgroundImageLayout = ImageLayout.Zoom;
ProductImages pI = output[i];
//Don't dispose the MemoryStream, the Image class will need it!
var ms = new MemoryStream(pI.Pic);
cb.BackgroundImage = Image.FromStream(ms);
flowLayoutPanel.Controls.Add(cb);
}
}
This is how you get your selected pictures:
private void SaveButton_Click(object sender, EventArgs e)
{
var selected = flowLayoutPanel.Controls.OfType<CheckBox>().Where(x => x.Checked);
Debug.Print("Selected images: {0}", selected.Count());
foreach (var item in selected)
{
//Save the picture from item.BackgroundImage.
}
}
I need to paint images from one panel to another panel like painting colors in a Windows Forms application but not colors, only Images.
I use an OpenFileDialog to open multiple images onto a panel and then paint those images by clicking on one and painting it with my mouse to the panel2.
My code for the openstripmenuitem:
private void openProjectToolStripMenuItem_Click(object sender, EventArgs e)
{
OpenFileDialog ofd = new OpenFileDialog();
ofd.Title = "Please select your files";
ofd.Multiselect = true;
ofd.Filter = "PNG|*.png|JPEG|*.jpeg|GIF|*.gif|TGA|*.tga|DDS|*.dds";
DialogResult dr = ofd.ShowDialog();
if (dr == System.Windows.Forms.DialogResult.OK)
{
string []files = ofd.FileNames;
int x = 20;
int y = 20;
int maxheight = -1;
foreach(string img in files)
{
PictureBox pic = new PictureBox();
pic.Image = Image.FromFile(img);
pic.Location = new Point(x, y);
pic.SizeMode = PictureBoxSizeMode.StretchImage;
x += pic.Width + 10;
maxheight = Math.Max(pic.Height, maxheight);
if (x > this.ClientSize.Width - 100)
{
x = 20;
y += maxheight + 10;
}
this.flowLayoutPanel1.Controls.Add(pic);
}
}
}
Any advice code examples welcome or link to references.
I am creating a simple image gallery where i require images that will load from a directory with their original names. i have used image list and list view control for this task .firstly i load images in image view control and by creating a thumbnail images are shown in list view control.
i am not able to get original name of images in list view control. i also want to get image's name while clicking the image.
Here is my Code
private void Form1_Load(object sender, EventArgs e)
{
DirectoryInfo dir = new DirectoryInfo(#"E:\mypics");
foreach (FileInfo file in dir.GetFiles())
{
imageList1.Images.Add(Image.FromFile(file.FullName));
}
listView1.View = View.LargeIcon;
imageList1.ImageSize = new Size(100, 100);
listView1.LargeImageList = this.imageList1;
ListViewItem item;
for (int i = 0; i < this.imageList1.Images.Count; i++)
{
item = new ListViewItem();
item.ImageIndex = i;
item.Text = "Image " + i.ToString();
listView1.Items.Add(item);
}
}
Show file in ListView control:
dir = new DirectoryInfo(Server.MapPath("~/Images/"));
lvImages.DataSource = dir.GetFiles("*.*");
lvImages.DataBind();
In design (show file name):
<asp:Literal ID="ltrImagePath" runat="server" Text='<%# Container.DataItem.ToString() %>'></asp:Literal>
I am very thankful to #Volodymyr Melnychuk who guided me up to what exactly was required.
private List _filenames;
private void Form1_Load(object sender, EventArgs e)
{
_filenames = new List();
DirectoryInfo dir = new DirectoryInfo(#"E:\mypics");
foreach (FileInfo file in dir.GetFiles())
{
var image = Image.FromFile(file.FullName);
_filenames.Add(file.Name);
imageList1.Images.Add(image);
}
listView1.View = View.LargeIcon;
imageList1.ImageSize = new Size(100, 150);
listView1.LargeImageList = imageList1;
for (int i = 0; i < imageList1.Images.Count; i++)
{
var item = new ListViewItem();
item.ImageIndex = i;
item.Text =_filenames[i];
listView1.Items.Add(item);
}
}
his above code is working but later i was required list view item name by double clicking onto it. i go t some help on MSDN.
here is the code.
private void listView1_MouseDoubleClick(object sender, MouseEventArgs e)
{
if (listView1.SelectedItems.Count == 1)
{
MessageBox.Show(listView1.SelectedItems[0].Text);
}
}
I have successfully imported and displayed horizontaly in a listView all the images from a folder/directory and now I want to be able to click on one of them and display that image in a big pictureBox above it called "mainPictureBox". I think I am close to that result, however what i have managed is to make the 100x100pixel image appear on the mainPictureBox that I clicked on from the listview rather than the high quality .PNG or .JPG from the folder. I'm guessing I need to use ImageKey or IndexKey or somehow associate the names of the images in the folder with the index of the clicked-on listView item. I am attaching an image of the GUI and the piece of code used for the imageList and listView if that helps.
http://i.imgur.com/GkF1hNd.jpg <---GUI screenshot
DirectoryInfo dir = new DirectoryInfo(#"C:\Users\UserName\Desktop\PhotoEditorProject\bin\Debug\Images");
foreach (FileInfo file in dir.GetFiles())
{
try
{
this.imageList1.Images.Add(Image.FromFile(file.FullName));
}
catch
{
Console.WriteLine("This is not an image file");
}
}
for (int i = 0; i < this.imageList1.Images.Count; i++)
{
ListViewItem item = new ListViewItem();
item.ImageIndex = i;
this.listView1.Items.Add(item);
}
my dear friend try this..
int b = 0;
public void button1_Click_1(object sender, EventArgs e)
{
var ofd = new OpenFileDialog();
ofd.Multiselect = true;
ofd.ShowDialog();
for (int z = 0; z < ofd.FileNames.Length; z++)
{
Image img = Image.FromFile(ofd.FileNames[z]);
string a = b.ToString();
imageList1.Images.Add(a, img);
var listViewItem = listView1.Items.Add(ofd.FileName );
listViewItem.ImageKey = a;
b++;
}
}
private void listView1_SelectedIndexChanged(object sender, EventArgs e)
{
string s= listView1.SelectedItems.ToString();
Bitmap bm= new Bitmap (#"" +s);
pictureBox1.Image = bm;
}
I am doing OCR application. I have this error when I run the system which the system will save the picturebox3.image into a folder.
//When user is selecting, RegionSelect = true
private bool RegionSelect = false;
private int x0, x1, y0, y1;
private Bitmap bmpImage;
private void loadImageBT_Click(object sender, EventArgs e)
{
try
{
OpenFileDialog open = new OpenFileDialog();
open.InitialDirectory = #"C:\Users\Shen\Desktop";
open.Filter = "Image Files(*.jpg; *.jpeg)|*.jpg; *.jpeg";
if (open.ShowDialog() == DialogResult.OK)
{
singleFileInfo = new FileInfo(open.FileName);
string dirName = System.IO.Path.GetDirectoryName(open.FileName);
loadTB.Text = open.FileName;
pictureBox1.Image = new Bitmap(open.FileName);
bmpImage = new Bitmap(pictureBox1.Image);
}
}
catch (Exception)
{
throw new ApplicationException("Failed loading image");
}
}
//User image selection Start Point
private void pictureBox1_MouseDown(object sender, MouseEventArgs e)
{
RegionSelect = true;
//Save the start point.
x0 = e.X;
y0 = e.Y;
}
//User select image progress
private void pictureBox1_MouseMove(object sender, MouseEventArgs e)
{
//Do nothing it we're not selecting an area.
if (!RegionSelect) return;
//Save the new point.
x1 = e.X;
y1 = e.Y;
//Make a Bitmap to display the selection rectangle.
Bitmap bm = new Bitmap(bmpImage);
//Draw the rectangle in the image.
using (Graphics g = Graphics.FromImage(bm))
{
g.DrawRectangle(Pens.Red, Math.Min(x0, x1), Math.Min(y0, y1), Math.Abs(x1 - x0), Math.Abs(y1 - y0));
}
//Temporary display the image.
pictureBox1.Image = bm;
}
//Image Selection End Point
private void pictureBox1_MouseUp(object sender, MouseEventArgs e)
{
// Do nothing it we're not selecting an area.
if (!RegionSelect) return;
RegionSelect = false;
//Display the original image.
pictureBox1.Image = bmpImage;
// Copy the selected part of the image.
int wid = Math.Abs(x0 - x1);
int hgt = Math.Abs(y0 - y1);
if ((wid < 1) || (hgt < 1)) return;
Bitmap area = new Bitmap(wid, hgt);
using (Graphics g = Graphics.FromImage(area))
{
Rectangle source_rectangle = new Rectangle(Math.Min(x0, x1), Math.Min(y0, y1), wid, hgt);
Rectangle dest_rectangle = new Rectangle(0, 0, wid, hgt);
g.DrawImage(bmpImage, dest_rectangle, source_rectangle, GraphicsUnit.Pixel);
}
// Display the result.
pictureBox3.Image = area;
** ERROR occuer here!!!!!**
area.Save(#"C:\Users\Shen\Desktop\LenzOCR\TempFolder\tempPic.jpg"); // error line occcur
singleFileInfo = new FileInfo("C:\\Users\\Shen\\Desktop\\LenzOCR\\TempFolder\\tempPic.jpg");
}
private void ScanBT_Click(object sender, EventArgs e)
{
var folder = #"C:\Users\Shen\Desktop\LenzOCR\LenzOCR\WindowsFormsApplication1\ImageFile";
DirectoryInfo directoryInfo;
FileInfo[] files;
directoryInfo = new DirectoryInfo(folder);
files = directoryInfo.GetFiles("*.jpg", SearchOption.AllDirectories);
var processImagesDelegate = new ProcessImagesDelegate(ProcessImages2);
processImagesDelegate.BeginInvoke(files, null, null);
//BackgroundWorker bw = new BackgroundWorker();
//bw.DoWork += new DoWorkEventHandler(backgroundWorker1_DoWork);
//bw.RunWorkerAsync(bw);
//bw.RunWorkerCompleted += new RunWorkerCompletedEventHandler(backgroundWorker1_RunWorkerCompleted);
}
private void ProcessImages2(FileInfo[] files)
{
var comparableImages = new List<ComparableImage>();
var index = 0x0;
foreach (var file in files)
{
if (exit)
{
return;
}
var comparableImage = new ComparableImage(file);
comparableImages.Add(comparableImage);
index++;
}
index = 0;
similarityImagesSorted = new List<SimilarityImages>();
var fileImage = new ComparableImage(singleFileInfo);
for (var i = 0; i < comparableImages.Count; i++)
{
if (exit)
return;
var destination = comparableImages[i];
var similarity = fileImage.CalculateSimilarity(destination);
var sim = new SimilarityImages(fileImage, destination, similarity);
similarityImagesSorted.Add(sim);
index++;
}
similarityImagesSorted.Sort();
similarityImagesSorted.Reverse();
similarityImages = new BindingList<SimilarityImages>(similarityImagesSorted);
var buttons =
new List<Button>
{
ScanBT
};
if (similarityImages[0].Similarity > 70)
{
con = new System.Data.SqlClient.SqlConnection();
con.ConnectionString = "Data Source=SHEN-PC\\SQLEXPRESS;Initial Catalog=CharacterImage;Integrated Security=True";
con.Open();
String getFile = "SELECT ImageName, Character FROM CharacterImage WHERE ImageName='" + similarityImages[0].Destination.ToString() + "'";
SqlCommand cmd2 = new SqlCommand(getFile, con);
SqlDataReader rd2 = cmd2.ExecuteReader();
while (rd2.Read())
{
for (int i = 0; i < 1; i++)
{
string getText = rd2["Character"].ToString();
Action showText = () => ocrTB.AppendText(getText);
ocrTB.Invoke(showText);
}
}
con.Close();
}
else
{
MessageBox.Show("No character found!", "Error!", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
#endregion
Since it has been a while, I'm hoping you found your answer, but I'm going to guess that you needed to set the file format when you're saving a jpeg:
area.Save(#"C:\Users\Shen\Desktop\LenzOCR\TempFolder\tempPic.jpg",System.Drawing.Imaging.ImageFormat.Jpeg);
Past that, I can't remember if the picturebox control is double buffered or not which could be the problem (if it's not, you might not be able to access it for saving purposes while it is being rendered, but if you make a copy of area before setting the picturebox3.Image property that would fix that issue):
Bitmap SavingObject=new Bitmap(area);
picturebox3.Image=area;
SavingObject.Save(#"C:\Users\Shen\Desktop\LenzOCR\TempFolder\tempPic.jpg",System.Drawing.Imaging.ImageFormat.Jpeg);
Anyway, I hope you ended up finding your solution (considering it's been a couple months since this was posted).
This looks like a copy of this question:
c# A generic error occurred in GDI+
Same code, same error, same author.
Can't see any difference. But maybe I'm missing something.