Foreach img in a folder i paint a picturebox on a panel, when i try to repaint the pictureboxes (after i remove one) the 'panel.controls.clear();' line gives a error:
Blockquote An unhandled exception of type 'System.ArgumentException' occurred in System.Drawing.dll Additional information: invalid parameter.
private void removeScreenshot_Click(object sender, EventArgs e)
{
Button btn = sender as Button;
PictureBox pb = btn.Parent as PictureBox;
string imgString = pb.Tag.ToString()
pb.BackgroundImage.Dispose();
pb.Image.Dispose();
try
{
File.Delete(imgString);
pb.Dispose();
}
catch (Exception ex)
{
Console.WriteLine("Cannot delete img: " + ex);
}
reload();
}
Below reload() function:
private void reload()
{
bool firstImg = true;
string[] fileList = Directory.GetFiles(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData) + "\\screenshots");
List<string> listOfStrings = new List<string>(fileList);
string supportedExtensions = "*.jpg,*.gif,*.png,*.bmp,*.jpe,*.jpeg";
listOfStrings.Reverse();
screenShotPanel.Controls.Clear();
if (listOfStrings.Count > 0)
{
foreach (string imgString in listOfStrings)
{
string extension = System.IO.Path.GetExtension(imgString);
if (supportedExtensions.Contains(extension))
{
PictureBox pb = new PictureBox();
pb.Click += new EventHandler(click_pb);
pb.MouseHover += new EventHandler(mouseHover_pb);
pb.MouseLeave += new EventHandler(mouseLeave_pb);
pb.Height = 100;
pb.Width = 100;
pb.Location = new Point(x, y);
Bitmap src = Image.FromFile(imgString) as Bitmap;
Bitmap cropped = CropBitmap(src, pb.Width, pb.Height);
Button removeScreenshot = new Button();
removeScreenshot.Height = 20;
removeScreenshot.Width = 20;
removeScreenshot.Location = new Point(80, 0);
removeScreenshot.BackColor = Color.Transparent;
removeScreenshot.ForeColor = Color.Transparent;
removeScreenshot.FlatStyle = FlatStyle.Flat;
removeScreenshot.FlatAppearance.BorderSize = 0;
removeScreenshot.MouseHover += new EventHandler(mouseHover_removeButton);
removeScreenshot.MouseLeave += new EventHandler(mouseLeave_removeButton);
removeScreenshot.Click += new EventHandler(removeScreenshot_Click);
pb.Controls.Add(removeScreenshot);
pb.BackgroundImage = src;
if (firstImg)
{
pictureBox.Image = src;
firstImg = false;
}
pb.Image = cropped;
pb.Tag = imgString;
pb.Name = Path.GetFileName(imgString);
screenShotPanel.Controls.Add(pb);
x = x + 120;
}
}
}
else
{
pictureBox.Image = null;
pictureBox.BackgroundImage = null;
}
}
The solution of the question is fixed by the following code:
using (var bmpTemp = new Bitmap(imgString))
{
src = new Bitmap(bmpTemp);
}
As replacement of this code:
Bitmap src = Image.FromFile(imgString) as Bitmap;
Related
I am doing C# application, and I want to change the style of a message box. Is it possible or not?
Example: change button style, fore color, etc.
You can't restyle the default MessageBox as that's dependant on the current Windows OS theme, however you can easily create your own MessageBox. Just add a new form (i.e. MyNewMessageBox) to your project with these settings:
FormBorderStyle FixedToolWindow
ShowInTaskBar False
StartPosition CenterScreen
To show it use myNewMessageBoxInstance.ShowDialog();. And add a label and buttons to your form, such as OK and Cancel and set their DialogResults appropriately, i.e. add a button to MyNewMessageBox and call it btnOK. Set the DialogResult property in the property window to DialogResult.OK. When that button is pressed it would return the OK result:
MyNewMessageBox myNewMessageBoxInstance = new MyNewMessageBox();
DialogResult result = myNewMessageBoxInstance.ShowDialog();
if (result == DialogResult.OK)
{
// etc
}
It would be advisable to add your own Show method that takes the text and other options you require:
public DialogResult Show(string text, Color foreColour)
{
lblText.Text = text;
lblText.ForeColor = foreColour;
return this.ShowDialog();
}
MessageBox::Show uses function from user32.dll, and its style is dependent on Windows, so you cannot change it like that, you have to create your own form
Here is the code needed to create your own message box:
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;
namespace MyStuff
{
public class MyLabel : Label
{
public static Label Set(string Text = "", Font Font = null, Color ForeColor = new Color(), Color BackColor = new Color())
{
Label l = new Label();
l.Text = Text;
l.Font = (Font == null) ? new Font("Calibri", 12) : Font;
l.ForeColor = (ForeColor == new Color()) ? Color.Black : ForeColor;
l.BackColor = (BackColor == new Color()) ? SystemColors.Control : BackColor;
l.AutoSize = true;
return l;
}
}
public class MyButton : Button
{
public static Button Set(string Text = "", int Width = 102, int Height = 30, Font Font = null, Color ForeColor = new Color(), Color BackColor = new Color())
{
Button b = new Button();
b.Text = Text;
b.Width = Width;
b.Height = Height;
b.Font = (Font == null) ? new Font("Calibri", 12) : Font;
b.ForeColor = (ForeColor == new Color()) ? Color.Black : ForeColor;
b.BackColor = (BackColor == new Color()) ? SystemColors.Control : BackColor;
b.UseVisualStyleBackColor = (b.BackColor == SystemColors.Control);
return b;
}
}
public class MyImage : PictureBox
{
public static PictureBox Set(string ImagePath = null, int Width = 60, int Height = 60)
{
PictureBox i = new PictureBox();
if (ImagePath != null)
{
i.BackgroundImageLayout = ImageLayout.Zoom;
i.Location = new Point(9, 9);
i.Margin = new Padding(3, 3, 2, 3);
i.Size = new Size(Width, Height);
i.TabStop = false;
i.Visible = true;
i.BackgroundImage = Image.FromFile(ImagePath);
}
else
{
i.Visible = true;
i.Size = new Size(0, 0);
}
return i;
}
}
public partial class MyMessageBox : Form
{
private MyMessageBox()
{
this.panText = new FlowLayoutPanel();
this.panButtons = new FlowLayoutPanel();
this.SuspendLayout();
//
// panText
//
this.panText.Parent = this;
this.panText.AutoScroll = true;
this.panText.AutoSize = true;
this.panText.AutoSizeMode = AutoSizeMode.GrowAndShrink;
//this.panText.Location = new Point(90, 90);
this.panText.Margin = new Padding(0);
this.panText.MaximumSize = new Size(500, 300);
this.panText.MinimumSize = new Size(108, 50);
this.panText.Size = new Size(108, 50);
//
// panButtons
//
this.panButtons.AutoSize = true;
this.panButtons.AutoSizeMode = AutoSizeMode.GrowAndShrink;
this.panButtons.FlowDirection = FlowDirection.RightToLeft;
this.panButtons.Location = new Point(89, 89);
this.panButtons.Margin = new Padding(0);
this.panButtons.MaximumSize = new Size(580, 150);
this.panButtons.MinimumSize = new Size(108, 0);
this.panButtons.Size = new Size(108, 35);
//
// MyMessageBox
//
this.AutoScaleDimensions = new SizeF(8F, 19F);
this.AutoScaleMode = AutoScaleMode.Font;
this.ClientSize = new Size(206, 133);
this.Controls.Add(this.panButtons);
this.Controls.Add(this.panText);
this.Font = new Font("Calibri", 12F, FontStyle.Regular, GraphicsUnit.Point, ((byte)(0)));
this.FormBorderStyle = FormBorderStyle.FixedSingle;
this.Margin = new Padding(4);
this.MaximizeBox = false;
this.MinimizeBox = false;
this.MinimumSize = new Size(168, 132);
this.Name = "MyMessageBox";
this.ShowIcon = false;
this.ShowInTaskbar = false;
this.StartPosition = FormStartPosition.CenterScreen;
this.ResumeLayout(false);
this.PerformLayout();
}
public static string Show(Label Label, string Title = "", List<Button> Buttons = null, PictureBox Image = null)
{
List<Label> Labels = new List<Label>();
Labels.Add(Label);
return Show(Labels, Title, Buttons, Image);
}
public static string Show(string Label, string Title = "", List<Button> Buttons = null, PictureBox Image = null)
{
List<Label> Labels = new List<Label>();
Labels.Add(MyLabel.Set(Label));
return Show(Labels, Title, Buttons, Image);
}
public static string Show(List<Label> Labels = null, string Title = "", List<Button> Buttons = null, PictureBox Image = null)
{
if (Labels == null) Labels = new List<Label>();
if (Labels.Count == 0) Labels.Add(MyLabel.Set(""));
if (Buttons == null) Buttons = new List<Button>();
if (Buttons.Count == 0) Buttons.Add(MyButton.Set("OK"));
List<Button> buttons = new List<Button>(Buttons);
buttons.Reverse();
int ImageWidth = 0;
int ImageHeight = 0;
int LabelWidth = 0;
int LabelHeight = 0;
int ButtonWidth = 0;
int ButtonHeight = 0;
int TotalWidth = 0;
int TotalHeight = 0;
MyMessageBox mb = new MyMessageBox();
mb.Text = Title;
//Image
if (Image != null)
{
mb.Controls.Add(Image);
Image.MaximumSize = new Size(150, 300);
ImageWidth = Image.Width + Image.Margin.Horizontal;
ImageHeight = Image.Height + Image.Margin.Vertical;
}
//Labels
List<int> il = new List<int>();
mb.panText.Location = new Point(9 + ImageWidth, 9);
foreach (Label l in Labels)
{
mb.panText.Controls.Add(l);
l.Location = new Point(200, 50);
l.MaximumSize = new Size(480, 2000);
il.Add(l.Width);
}
int mw = Labels.Max(x => x.Width);
il.ToString();
Labels.ForEach(l => l.MinimumSize = new Size(Labels.Max(x => x.Width), 1));
mb.panText.Height = Labels.Sum(l => l.Height);
mb.panText.MinimumSize = new Size(Labels.Max(x => x.Width) + mb.ScrollBarWidth(Labels), ImageHeight);
mb.panText.MaximumSize = new Size(Labels.Max(x => x.Width) + mb.ScrollBarWidth(Labels), 300);
LabelWidth = mb.panText.Width;
LabelHeight = mb.panText.Height;
//Buttons
foreach (Button b in buttons)
{
mb.panButtons.Controls.Add(b);
b.Location = new Point(3, 3);
b.TabIndex = Buttons.FindIndex(i => i.Text == b.Text);
b.Click += new EventHandler(mb.Button_Click);
}
ButtonWidth = mb.panButtons.Width;
ButtonHeight = mb.panButtons.Height;
//Set Widths
if (ButtonWidth > ImageWidth + LabelWidth)
{
Labels.ForEach(l => l.MinimumSize = new Size(ButtonWidth - ImageWidth - mb.ScrollBarWidth(Labels), 1));
mb.panText.Height = Labels.Sum(l => l.Height);
mb.panText.MinimumSize = new Size(Labels.Max(x => x.Width) + mb.ScrollBarWidth(Labels), ImageHeight);
mb.panText.MaximumSize = new Size(Labels.Max(x => x.Width) + mb.ScrollBarWidth(Labels), 300);
LabelWidth = mb.panText.Width;
LabelHeight = mb.panText.Height;
}
TotalWidth = ImageWidth + LabelWidth;
//Set Height
TotalHeight = LabelHeight + ButtonHeight;
mb.panButtons.Location = new Point(TotalWidth - ButtonWidth + 9, mb.panText.Location.Y + mb.panText.Height);
mb.Size = new Size(TotalWidth + 25, TotalHeight + 47);
mb.ShowDialog();
return mb.Result;
}
private FlowLayoutPanel panText;
private FlowLayoutPanel panButtons;
private int ScrollBarWidth(List<Label> Labels)
{
return (Labels.Sum(l => l.Height) > 300) ? 23 : 6;
}
private void Button_Click(object sender, EventArgs e)
{
Result = ((Button)sender).Text;
Close();
}
private string Result = "";
}
}
Getting error when its casting in Listview:
private void listView1_SelectedIndexChanged(object sender, EventArgs e)
{
int a = 1;
string theimage = textBox1.Text + #"\allimages\";
foreach (ListViewItem item in listView1.SelectedItems)
{
// 39 zero's + "1"
string initValue = new String('0', 3) + "0";
// convert to int and add 1
int newValue = Int32.Parse(initValue) + a;
// convert back to string with leading zero's
string newValueString = newValue.ToString().PadLeft(4, '0');
string imageslist = "product" + newValueString + "img";
string[] images = Directory.GetFiles(theimage, imageslist + "*.jpg");
// Cast the Picturebox
PictureBox myPicBox = new PictureBox();
myPicBox.Location = new Point(7, 240);
myPicBox.Size = new System.Drawing.Size(140, 140);
myPicBox.SizeMode = PictureBoxSizeMode.AutoSize;
myPicBox.Margin = new Padding(3,3,3,3);
myPicBox.Visible = true;
myPicBox.Image = new Bitmap(images[1]);
Controls.Add(myPicBox);
System.Diagnostics.Debugger.Break();
//List<PictureBox> pictureBoxList = new List<PictureBox>();
}
}
Its my error:
Error 1 'test.Form1.PictureBoxSizeMode()' is a 'method', which is not valid in the given context C:\Users\radiaku\Documents\Visual Studio 2008\Projects\test\test\Form1.cs 428 37 test
the code above working fine when I using button_click handler..
It sounds like your form has a method called PictureBoxSizeMode. You could either change the method name, or change the property setter to:
myPicBox.SizeMode = System.Windows.Forms.PictureBoxSizeMode.AutoSize;
Changing the method name would be cleaner though.
That error can only occur if you have a method named PictureBoxSizeMode in your code. You should rename that method to something else. A scenario like:
private void UserInput_KeyPress(object sender, KeyPressEventArgs e)
{
PictureBox myPicBox = new PictureBox();
myPicBox.Location = new Point(7, 240);
myPicBox.Size = new System.Drawing.Size(140, 140);
myPicBox.SizeMode = PictureBoxSizeMode.AutoSize;
myPicBox.Margin = new Padding(3, 3, 3, 3);
myPicBox.Visible = true;
}
private void PictureBoxSizeMode()
{
}
Or qualify it with the Namespace like.
myPicBox.SizeMode = myPicBox.SizeMode = System.Windows.Forms.PictureBoxSizeMode.AutoSize;
i want to convert a string entered by user to an image..how can it be done?
i tried the following code but i get an argument exception in the line :
WriteableBitmap wbimg = PictureDecoder.DecodeJpeg(memStream);
static public string EncodeTo64(string toEncode)
{
byte[] toEncodeAsBytes
= StringToAscii(toEncode);
string returnValue
= System.Convert.ToBase64String(toEncodeAsBytes);
return returnValue;
}
public static byte[] StringToAscii(string s)
{
byte[] retval = new byte[s.Length];
for (int ix = 0; ix < s.Length; ++ix)
{
char ch = s[ix];
if (ch <= 0x7f) retval[ix] = (byte)ch;
else retval[ix] = (byte)'?';
}
return retval;
}
void convert()
{
String s = textBox1.Text;
byte[] data = Convert.FromBase64String(EncodeTo64(s));
for (int i = 0; i < data.Length; i++)
{
System.Diagnostics.Debug.WriteLine(data[i]);
}
Stream memStream = new MemoryStream();
memStream.Write(data, 0, data.Length);
try
{
WriteableBitmap wbimg = PictureDecoder.DecodeJpeg(memStream);
image1.Source = wbimg;
}
catch (Exception e)
{
MessageBox.Show(e.ToString());
}
}
I got what i wanted in the following links.. How can I render text on a WriteableBitmap on a background thread, in Windows Phone 7? and http://blogs.u2u.be/michael/post/2011/04/20/Adding-a-text-to-an-image-in-WP7.aspx Thanks to all those who replied for the initial help! :)
It is the simple way you can convert TextBlock Text into Image
private void convert_Click(object sender, RoutedEventArgs e)
{
Canvas c1 = new Canvas();
TextBlock t = new TextBlock();
t.Text = text1.Text;
t.FontFamily = text1.FontFamily;
t.Foreground = text1.Foreground;
t.FontSize = text1.FontSize;
c1.Children.Add(t);
WriteableBitmap wbmp = new WriteableBitmap(c1, null);
im = new Image();
im.Source = wbmp;
im.Height = 200;
im.Width = 200;
Canvas.SetTop(im, 10);
Canvas.SetLeft(im, 10);
Main_Canvas.Children.Add(im);
}
Here I convert the Textblock Text into Bitmap and then assign it to the image source.
Here is how to writte a string to a bitmap:
Bitmap b = new Bitmap(200, 100);
Graphics g = Graphics.FromImage(b);
g.DrawString("My sample string", new Font("Tahoma",10), Brushes.Red, new Point(0, 0));
b.Save("mypic.png", System.Drawing.Imaging.ImageFormat.Png);
g.Dispose();
b.Dispose();
Shubhi1910 let me know if you need any details to be explained.
I am trying to add border in two pivot items.
When my border is added to grid in pivot item for the first time everything is working fine. But when i try to add border second time in same pivot item it throws an exception "The parameter is incorrect"
here is my code :
private void pivot_item1Loaded()
{
WebClient webClient2011 = new WebClient();
string Url2011 = "http://hostname/Details/Images?year=2011" + "&time=" + System.DateTime.UtcNow;
webClient2011.OpenReadAsync(new Uri(Url2011));
webClient2011.OpenReadCompleted += new OpenReadCompletedEventHandler(webClient_OpenReadCompleted2011);
}
private void pivot_item2Loaded()
{
WebClient webClient2012 = new WebClient();
string Url2012 = "http://hostname/Details/Images?year=2012" +"&time="+ System.DateTime.UtcNow;
webClient2012.OpenReadAsync(new Uri(Url2012));
webClient2012.OpenReadCompleted += new OpenReadCompletedEventHandler(webClient_OpenReadCompleted2012);
}
public void webClient_OpenReadCompleted2011(object sender, OpenReadCompletedEventArgs e)
{
StringBuilder output = new StringBuilder();
try
{
using (XmlReader reader = XmlReader.Create(e.Result))
{
while (reader.Read())
{
if (reader.NodeType == XmlNodeType.Element)
{
if (reader.Name == "iconPath")
{
string iconPath = reader.ReadElementContentAsString();
iconImages2011.Add(iconPath);
}
if (reader.Name == "imagePath")
{
string imagePath = reader.ReadElementContentAsString();
fullScreenImages2011.Add(imagePath);
}
}
}
}
int numOfRows = (iconImages2011.Count) / 3 + 1;
for (int j = 0; j < numOfRows; j++)
{
//pivot_item1
ContentPanel2011.RowDefinitions.Add(new RowDefinition() { Height = new GridLength(150) });
}
int rowCount = 0;
int columnCount = 0;
for (int i = 0; i < iconImages2011.Count; i++)
{
Border border2011 = new Border();
border2011.Background = new SolidColorBrush(Colors.Blue);
border2011.Height = 110;
border2011.Width = 110;
border2011.CornerRadius = new CornerRadius(10);
Canvas canvas2011 = new Canvas();
canvas2011.Height = 110;
canvas2011.Width = 110;
BitmapImage AppImage = new BitmapImage(new Uri(iconImages2011[i], UriKind.Absolute));
Image img = new Image();
img.Source = AppImage;
img.Width = 90;
img.Height = 90;
img.Stretch = Stretch.Fill;
img.Margin = new Thickness(10, 10, 10, 10);
canvas2011.Children.Add(img);
border2011.Child = canvas2011;
border2011.Name = i.ToString();
Grid.SetColumn(border2011, columnCount);
Grid.SetRow(border2011, rowCount);
ContentPanel2011.Children.Add(border2011);
pivot2011.Content = ContentPanel2011;
if (columnCount < 2)
{
columnCount++;
}
else if (columnCount == 2)
{
columnCount = 0;
rowCount++;
}
}
}
catch (Exception x)
{
MessageBox.Show(x.Message);
}
}
This code works for the first time but gives exception after that and ContentPanel2011 viz pivot_item1 do not get filled with border2011
It is done.
just set content property on pivots to null before before setting the content again.
I have just added:
pivot2011.Content = null;
pivot2012.Content = null;
in pivot_item1Loaded() and pivot_item2Loaded()
and it is working fine.
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.