How to get Images from database to Listview c# - c#

I want to get database images show in listview but it does not work . I tried but can't any one can help .
ListViewItem liv = new ListViewItem(read[0].ToString());
liv.SubItems.Add(read[1].ToString());
liv.SubItems.Add(read[2].ToString());
liv.SubItems.Add(read[3].ToString());
listView1.Items.Add(liv);
Here on index[3] in database the images stored .
The error show in image

For what I can see, your image is stored in a Database and retrieved in ByteArray format. You need to convert the ByteArray stream to a Bitmap Image:
Image _image = new Bitmap(new MemoryStream((Byte[])read[3]));
Since this image has to be referenced in more than one method, define it at Class level.
using System.Drawing;
using System.Drawing.Text;
Image _image;
To let a SubItem display the image, you need to Paint the items yourselft, so set the OwnerDraw property of your ListView:
listView1.OwnerDraw = true;
Get the items from your Data source:
(... LOOP ...)
//Define a new ListView Item...
ListViewItem _LVItem = new ListViewItem(read[0].ToString());
ListViewItem.ListViewSubItemCollection _ItemsCollection =
new ListViewItem.ListViewSubItemCollection(_LVItem);
//... and SubItems
_ItemsCollection.Add(new ListViewItem.ListViewSubItem(_LVItem, read[1].ToString()));
_ItemsCollection.Add(new ListViewItem.ListViewSubItem(_LVItem, read[2].ToString()));
//No text here, this is where the image will be drawn
_ItemsCollection.Add(new ListViewItem.ListViewSubItem(_LVItem, ""));
//Create a new Bitmap using a MemoryStream
_image = new Bitmap(new MemoryStream((Byte[])read[3]));
listView1.Items.Add(_LVItem);
(... LOOP ...)
Create EventHandlers for listView1.DrawColumnHeader and listView1.DrawSubItem
//You need to draw both Headers...
private void listView1_DrawColumnHeader(object sender, DrawListViewColumnHeaderEventArgs e)
{
e.Graphics.TextRenderingHint = TextRenderingHint.ClearTypeGridFit;
//Let the system draw these headers, nothing to do here
e.DrawDefault = true;
}
//... and SubItems
private void listView1_DrawSubItem(object sender, DrawListViewSubItemEventArgs e)
{
//If this is the column where the image is shown, draw it
if (e.ColumnIndex == 3)
{
//Position the image in the middle of its Column
//This will be re-calculated when the Column is resized
int _XLocation = (e.SubItem.Bounds.X +
(e.SubItem.Bounds.Width / 2) -
(e.SubItem.Bounds.Height / 2));
//Draw the Image resized to the Height of the row
e.Graphics.DrawImage(_image, new Rectangle(_XLocation, e.SubItem.Bounds.Y, e.SubItem.Bounds.Height, e.SubItem.Bounds.Height));
}
//Draw the other columns using their pre-defined values
e.Graphics.TextRenderingHint = System.Drawing.Text.TextRenderingHint.ClearTypeGridFit;
e.Graphics.DrawString(e.SubItem.Text,
e.SubItem.Font,
new SolidBrush(e.SubItem.ForeColor),
e.SubItem.Bounds.Location.X,
e.SubItem.Bounds.Location.Y);
}
And this is the result:

// To Convert you byte array to Images you need to convert it to a memory stream first
// You will need to add:
// using System.IO;
// And you need to add an ImageList named "imageList1" to your form.
// Then Initialize the ImageList object with images.
for (int i = 0; i < read.Length; i++)
{
try
{
MemoryStream memStream = new MemoryStream(read[i]);
this.imageList1.Images.Add(Image.FromStream(memStream));
}
catch
{ MessageBox.Show( "Image at index ( " + i.ToString() + " ) is not an image file"); }
}
//Now You can assign the ImageList objects to your ListView.
this.listView1.View = View.SmallIcon;
this.listView1.SmallImageList = this.imageList1;
for (int j = 0; j < this.imageList1.Images.Count; j++)
{
ListViewItem liv = new ListViewItem();
liv.ImageIndex = j;
this.listView1.Items.Add(liv);
}

Related

how can I select the pictures loaded in windows Form in c#?

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

Trying to read pixel color from PictureBox in C# WinForms

I am having an odd issue whereby when I then try to iterate over the pixels of the PictureBox or save the bmp it is just all black.
The intention of the tool is that you select a font, size, and style, and then it loops over the ASCII chars of that font and shows each character in the picture box, and converts the pixel data into a HEX array so I can use them on LCD displays.
The main part of the tool works whereby it is correctly looping through the ASCII chars and displaying them in the picture box but after each char is drawn to the picture box and I then try to iterate over the pixels of the PictureBox every pixel is returned as 0,0,0 RGB "black" and if I save the bmp which was drawn to the PictureBox that too is all black, but again I can see the bmp of that char correct drawn in the PictureBox yet the PictureBox data and bmp data does not match what I see in the PictureBox itself, I am truly lost as to why I am unable to correctly iterate or save the bmp or PictureBox.
I have tried not using async functions which is not ideal as I want the UI to be free, and I have tried various means to read the pixels and save the bmp but the result is the same. I hope to ask if anyone knows why I am getting this odd behavior and the solution to the issue.
Regards from Ed.
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using System.IO;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace generateFonts
{
public partial class Form1 : Form
{
string font = "";
float fontSize = 0;
FontStyle fontStyle = FontStyle.Regular;
public Form1()
{
InitializeComponent();
comboBox1.SelectedIndex = 0;
comboBox2.SelectedIndex = 0;
comboBox3.SelectedIndex = 0;
font = comboBox1.SelectedItem.ToString();
fontSize = Convert.ToInt32(comboBox2.SelectedItem);
fontStyle = FontStyle.Regular;
}
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
font = comboBox1.SelectedItem.ToString();
}
private void comboBox2_SelectedIndexChanged(object sender, EventArgs e)
{
fontSize = Convert.ToInt32(comboBox2.SelectedItem);
}
private void comboBox3_SelectedIndexChanged(object sender, EventArgs e)
{
if (comboBox3.SelectedIndex == 0)
fontStyle = FontStyle.Regular;
else if (comboBox3.SelectedIndex == 1)
fontStyle = FontStyle.Italic;
else if(comboBox3.SelectedIndex == 2)
fontStyle = FontStyle.Bold;
}
private async void button1_Click(object sender, EventArgs e)
{
await Task.Run(() => StartProcess(1));
}
private void StartProcess(int runs)
{
// Font
Font myFont = new Font(font, fontSize, fontStyle);
List<string> bytes = new List<string>();
string[] bits = { "0", "0", "0", "0", "0", "0", "0", "0" };
byte bitPos = 0;
for (byte i = 32; i < 126; i++)
{
//Create a Image-Object on which we can paint
Image bmp = new Bitmap(200, 200);
//Create the Graphics-Object to paint on the Bitmap
Graphics g = Graphics.FromImage(bmp);
string c = Convert.ToChar(i).ToString();
//Get the perfect Image-Size so that Image-Size = String-Size
SizeF size = g.MeasureString(c, myFont);
//Use this to become better Text-Quality on Bitmap.
g.TextRenderingHint = System.Drawing.Text.TextRenderingHint.AntiAlias;
g.InterpolationMode = InterpolationMode.HighQualityBicubic;
g.PixelOffsetMode = PixelOffsetMode.HighQuality;
//Here we draw the string on the Bitmap
g.DrawString(c, myFont, new SolidBrush(Color.Black), 0, 0);
if (!Directory.Exists("FontBmps"))
Directory.CreateDirectory("FontBmps");
this.Invoke((MethodInvoker)delegate ()
{
pictureBox2.Width = Convert.ToInt32(size.Width);
pictureBox2.Height = Convert.ToInt32(size.Height);
pictureBox2.Image = bmp; // <--- this is working and the picturebox shows the bmp correctly
bmp.Save("FontBmps/" + i + "_" + font + "_" + fontSize + "px_" + fontStyle + ".bmp", ImageFormat.Bmp); // <--- error here: this saves a black square instead of the bmp i see displayed in the picturebox GUI ??
// Even if i save the picturebox itself that too is just a black square instead of the correct image shown in the GUI ??
// now convert the bmp to a HEX array of pixels
for (int h = 0; h < pictureBox2.Height; h++)
{
for (int w = 0; w < pictureBox2.Width; w++)
{
Color colour = (pictureBox2.Image as Bitmap).GetPixel(w, h);
if (colour.R == 0 && colour.G == 0 && colour.B == 0)
{
bits[bitPos] = "1";
}
else
{
bits[bitPos] = "0"; // <-- never hits me, again for some reason the bmp or picturebox is all black pixels data but i see it correctly show in the picturebox GUI ??
}
if (bitPos < 7)
bitPos++;
else
{
//string bitStr = bits.ToString();
//string hex = Convert.ToByte(bitStr, 2).ToString("x2");
//bytes.Add(hex);
bitPos = 0;
for(byte n = 0; n < 8; n++)
{
bits[n] = "0";
}
}
}
}
if (bitPos != 0)
{
// TO DO...
}
});
Thread.Sleep(500); // <--- i have this just to see it displaying the chars but i have removed it with no effect to the issue
}
// now add List to a file in the correct format
foreach (string str in bytes)
{
Console.WriteLine(str);
// TO DO...
}
}
}
}
I believe the image is black, but some parts have transparency. That is, you would need to check Alpha (Color.A). What you see in the picture box, would be the background color of the picture box where it is transparent.
You won't see the transparency in the saved file, given that the ImageFormat.Bmp does not support transparency. Try Png instead, which supports transparency (and has lossless compression).
Alternatively, you can use Graphics.Clear to have the image be the color you want for background (white, I guess) before drawing to it.
Aside from that, I'll suggest to use bmp instead of (pictureBox2.Image as Bitmap), and use Bitmap.LockBits. That would improve performance.
This might be useful for reference: Converting a bitmap to monochrome. See also C# - Faster Alternatives to SetPixel and GetPixel for Bitmaps for Windows Forms App.

How to load image to PictureBox list

I am loading images like this:
image = Image.FromFile(//here goes path to image);
Than i have list of pictureBoxes like this
List<PictureBox> pictureBoxes = new List<PictureBox>();
Than i load picture boxes in pictureBox list like this
// i is set to one
for (; i < this.images.Count; i++)
{
pictureBoxes.Add((PictureBox)Controls.Find("pictureBox" + i.ToString(), true)[0]);
}
And now I want to load that image in pictureBox[0]. Then I load another image and I want to add it to pictureBox[1] and so on. I am trying to do this more than 3 days. Does anyone know how to do it?
After you filled your picturebox list, just find the first empty one.
var emptyPb = pictureBoxes.Where(x => x.Image == null).FirstOrDefault();
if(emptyPb==null)
{
throw new Exception("No empty picturebox could be found!");
return;
}
emptyPb.Image = images[0];
//Set the number of images you have.
int imageCount = 3;
//Create path.
string path = #"C:\ImageFolder\";
//Create the List of PictureBox
List<PictureBox> pictureBoxes = new List<PictureBox>();
//This for will create the name foreach image.
//Example: "pic1", "pic2", "pic3".
//Assuming that you have the names of each file image like the example.
for (int i = 1; i < imageCount + 1; i++)
{
//Create a PictureBox foreach image
PictureBox pictureBox = new PictureBox()
{
Name = $"pic{i}",
//Assign the image file.
Image = Image.FromFile(path + $"pic{i}.jpg")
};
//Add the new pictureBox to the list pictureBoxes
pictureBoxes.Add(pictureBox);
}

How to Drag&Drop Outlook-Mail into richTextBox

I got a problem with my WinForms-Application; I want to Drag&Drop a Outlook Mail into a RichTextBox. I found many articles about the Drag&Drop function but they all insert the Mailtext into the rTB (see: Link).Actually I can insert document like .txt, .jpg, Outlook-mails from desktop... to my program. My richTextBox automatic generate an image for the file and insert this image on a position. Like:
.
After the user Drag and Drop the file a image will be created on the Drop position and if the user double click the image the file will be opened.
PROBLEM:
The program work fine, but if I try to drag a mail out of Outlook, the program insert the mailbody to the richTextBox and no as an image.
I have saved one Mail on the desktop and try to insert this mail to my program. The following output is given in my richTextBox (would be perfect):
Mailicon from desktop per Drag&Drop:
Otherwise I tried to Drag&Drop a mai from Outlook to my program and the following output is given (Just look at the text and not the images:
Mail from Outlook per Drag&Drop (THE PROBLEM!!!):
The Programm insert the cc/mailadress and Mailbody to the rTB.
Here is the code behind: (My richTextBox is a own created richTextBox called "MyRichTextBox" Download the project under: link_RICHTEXTBOX. )
CODE
private void Form1DragDrop(object sender, DragEventArgs e)
{
Startup();
//Microsoft.Office.Interop.Outlook.ApplicationClass oApp =
// new Microsoft.Office.Interop.Outlook.ApplicationClass();
Microsoft.Office.Interop.Outlook.Explorer oExplorer = _Outlook.ActiveExplorer();
Microsoft.Office.Interop.Outlook.Selection oSelection = oExplorer.Selection;
foreach (object item in oSelection)
{
Microsoft.Office.Interop.Outlook.MailItem mi = (Microsoft.Office.Interop.Outlook.MailItem)item;
rTB_test.Text = mi.Body.ToString();
string mailName = "Mail\n" + (mailList.Count + 1);
// load an image with enough room at the bottom to add some text:
Image img = Image.FromFile(Imagepath);
// now we add the text:
int width = img.Width;
using (Graphics G = Graphics.FromImage(img))
using (Font font = new Font("Arial", 7f))
{
SizeF s = G.MeasureString(mailName, font, width);
G.DrawString(mailName, font, Brushes.Black,
(width - s.Width) / 2, img.Height - s.Height - 1);
}
// adding the image is easy only if we use the clipboard..
Clipboard.SetImage(img);
// now insert image
rTB_test.Paste();
// now we can get a hashcode as a unique key..
// ..we select the image we have just inserted:
rTB_test.SelectionStart = rTB_test.TextLength - 1;
rTB_test.SelectionLength = 1;
// finally we need to store the mail itself with its key:
mailList.Add(rTB_test.SelectedRtf.GetHashCode(), mi);
// cleanup: unselect and set cursor to the end:
rTB_test.SelectionStart = rTB_test.TextLength;
rTB_test.SelectionLength = 0;
}
Microsoft.Office.Interop.Outlook.Application _Outlook = null;
Dictionary<int, Microsoft.Office.Interop.Outlook.MailItem> mailList =
new Dictionary<int, Microsoft.Office.Interop.Outlook.MailItem>();
private void rTB_test_DoubleClick(object sender, EventArgs e)
{
var ss = rTB_test.SelectionStart;
var sl = rTB_test.SelectionLength;
int hash = rTB_test.SelectedRtf.GetHashCode();
// a few checks:
if (sl == 1 && mailList.Keys.Contains(hash))
{
Microsoft.Office.Interop.Outlook.MailItem mi = mailList[hash];
// do stuff with the msgItem..
// ..
}
}
void lbl_MouseDoubleClick(object sender, MouseEventArgs e)
{
Microsoft.Office.Interop.Outlook.MailItem mi =
(Microsoft.Office.Interop.Outlook.MailItem)((Label)sender).Tag;
// code to process the doubleclicked mail item..
}
void Startup()
{
_Outlook = new Microsoft.Office.Interop.Outlook.Application();
}
private void Form1_DragEnter(object sender, DragEventArgs e)
{
e.Effect = DragDropEffects.Copy;
}
After the user double click on the picture the mail should be opened in Outlookexplorer.
UPDATE
If I use the code from TaW´s answer the following output is given:
After I double click the icon the mail won´t be open... So the code from the answer is just a "iconcreation".
Thank you in advanced!
Here is what I meant in my comments:
private void Form1DragDrop(object sender, DragEventArgs e)
{
Startup();
Microsoft.Office.Interop.Outlook.ApplicationClass oApp =
new Microsoft.Office.Interop.Outlook.ApplicationClass();
Microsoft.Office.Interop.Outlook.Explorer oExplorer = _Outlook.ActiveExplorer();
Microsoft.Office.Interop.Outlook.Selection oSelection = Explorer.Selection;
foreach (object item in oSelection)
{
Microsoft.Office.Interop.Outlook.MailItem mi =
(Microsoft.Office.Interop.Outlook.MailItem)item;
// rTB_test.Text = mi.Body.ToString();
Label lbl = new Label();
lbl.AutoSize = false;
lbl.Size = new Size( 80, 50); // <-- your choice!
lbl.Text = someText; // <-- your choice!
lbl.TextAlign = ContentAlignment.BottomCenter;
lbl.Image = someImage; // <-- your choice!
lbl.ImageAlign = ContentAlignment.TopCenter;
int count = rTB_test.Controls.Count;
int itemsPerRow = rTB_test.Width / 80;
lbl.Location = new Point( (count % itemsPerRow) * 80,
count / itemsPerRow * 50);
lbl.Tag = mi; // store the data object
lbl.MouseDoubleClick += lbl_MouseDoubleClick;
lbl.Parent = rTB_test; // add to the RTF's Controls
}
}
void lbl_MouseDoubleClick(object sender, MouseEventArgs e)
{
Microsoft.Office.Interop.Outlook.MailItem mi =
(Microsoft.Office.Interop.Outlook.MailItem) ( (Label)sender).Tag;
// code to process the doubleclicked mail item..
}
These Labels will sit on top of any Text in the RTB without interfering with it. If you want to, you can modify the code for the Location to move them out of the way or style the Labels in many other ways..
Update
After the last remarks the problem get a lot clearer: other parts of the application are already adding mail icons to the RTB and we shall add more 'of the same'..
Adding an Image is best done via the clipboard; here is code that will do that:
// create some test text, maybe extract it from the mailheader?..
string mailName = "Mail\n" + (mailList.Count + 1);
// load an image with enough room at the bottom to add some text:
Image img = Image.FromFile(yourMailImageFile);
// make the images unique by embedding a counter in a bright pixel:
img = (Image)fingerPrintID((Bitmap)img, 250 - mailList.Count); //*1*
// now we add the text:
int width = img.Width;
using (Graphics G = Graphics.FromImage(img))
using (Font font = new Font("Arial", 7f))
{
SizeF s = G.MeasureString(mailName, font, width);
G.DrawString(mailName, font, Brushes.Black,
(width - s.Width) / 2, img.Height - s.Height - 1);
}
// adding the image is easy only if we use the clipboard..
Clipboard.SetImage(img);
// insert only at the end!
rTB_test.SelectionStart = rTB_test.TextLength;
rTB_test.SelectionLength = 0;
// now insert image
rTB_test.Paste();
// now we can get a hashcode as a unique key..
// ..we select the image we have just inserted:
rTB_test.SelectionStart = rTB_test.TextLength - 1;
rTB_test.SelectionLength = 1;
// retrieve the counter id:
string id = GetID(rTB_test.SelectedRtf); //*2*
// finally we need to store the mail itself with its key:
mailList.Add(id, mi);
// cleanup: unselect and set cursor to the end:
rTB_test.SelectionStart = rTB_test.TextLength;
rTB_test.SelectionLength = 0
We need to create a Dictionary to store our mails:
Dictionary<string, Microsoft.Office.Interop.Outlook.MailItem> mailList =
new Dictionary<string, Microsoft.Office.Interop.Outlook.MailItem>(); // *3*
Here is how we can access the mails in the DoubleClick event:
private void rTB_test_DoubleClick(object sender, EventArgs e)
{
var ss = rTB_test.SelectionStart;
var sl = rTB_test.SelectionLength;
string id = GetID(sr); //*4*
// a few checks:
if (sl == 1 && mailList.Keys.Contains(id) && sr.Contains(#"{\pict\") )
{
Microsoft.Office.Interop.Outlook.MailItem mi = mailList[id];
// do stuff with the msgItem, e.g..
mi.Display();
}
}
Here is the result along with the image I use:
Note that in addition to adding the image we also store the both the mail data and the position of the image in the RTB in a Dictionary.
Update 2: I have replaced the position of the image as key with a HashCode of its RtfText; this is robust to any changes in the rest of the RTF's content. However, it relies on the images being unique, so adding an index to their text as in the code is recommended. (Or setting a few random pixels, maybe based on a GUID..)
Update 3 & 4: (*1* - *6*)
We found that we need to make the key resilient to several changes, like fonts surrounding the icon, which will influence the Rtf code, or the user enlarging the image.
Here is a FingerPrint function, which will make the images we add in unobtrusivly unique by setting a few pixels at the top of the image. Three to set a marker and one to set an ID:
Bitmap fingerPrintID(Bitmap bmp, int key) //*5*
{
for (int i = 0; i < 3; i++)
{
bmp.SetPixel(i, 0, Color.FromArgb(255, 238,238,238)); // EE EE EE
}
bmp.SetPixel(3, 0, Color.FromArgb(255, key, key, key));
return bmp;
}
And to retrieve this function will pull the 3 hex digits as string from the RTF code:
string GetID(string Rtf) //*6*
{
int x = Rtf.IndexOf("eeeeeeeeeeeeeeeeee"); // 238 238 238
if (x < 0) return "";
string hex = Rtf.Substring(x +18, 6);
return hex;
}
I chose the pixels to be rather bright; if you know which image you use, you can optimze the color choice even more.. With the new string id, we don't need the GetHashcode calls..

Clicking on an image in a listView and making it appear in a pictureBox

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

Categories