Here is my small software.. We add images clicking "ADD YOUR QR CODE" and it will be displayed on pictureBoxLoad picturebox, After that i will crop the image. Then it shows on picturebox2.
But my problem is ,it is only shows on picturebox2, But picturebox2.image is null...how to fix that error. I want to add cropping image to picturebox2 without null..
here after clicking the crop button
here is the code i tried
{
int xDown = 0;
int yDown = 0;
int xUp = 0;
int yUp = 0;
Rectangle rectCropArea = new Rectangle();
System.IO.MemoryStream ms = new System.IO.MemoryStream();
Task timeout;
string fn = "";
public Main()
{
InitializeComponent();
}
private void Main_Load(object sender, EventArgs e)
{
}
private void selectIm_Click(object sender, EventArgs e)
{
OpenFileDialog opf = new OpenFileDialog();
if (opf.ShowDialog() == DialogResult.OK)
{
PictureBoxLoad.Image = Image.FromFile(opf.FileName);
fn = opf.FileName;
}
PictureBoxLoad.Cursor = Cursors.Cross;
}
private void PictureBoxLoad_MouseUp(object sender, MouseEventArgs e)
{
}
private void PictureBoxLoad_MouseDown(object sender, MouseEventArgs e)
{
}
private void crop_Click(object sender, EventArgs e)
{
}
private void button1_Click(object sender, EventArgs e)
{
OpenFileDialog opf = new OpenFileDialog();
opf.Filter= "Image Files(*.jpg; *.jpeg; *.gif;*.png; *.bmp)|*.jpg; *.jpeg; *.gif; *.bmp;*.png";
if (opf.ShowDialog() == DialogResult.OK)
{
PictureBoxLoad.Image = Image.FromFile(opf.FileName);
fn = opf.FileName;
}
PictureBoxLoad.Cursor = Cursors.Cross;
}
private void button2_Click(object sender, EventArgs e)
{
string root = #"C:\FuePass";
// If directory does not exist, create it.
if (!System.IO.Directory.Exists(root))
{
System.IO.Directory.CreateDirectory(root);
}
Bitmap bmp = new Bitmap(previewimg.Width, previewimg.Height);
previewimg.DrawToBitmap(bmp, new Rectangle(0, 0, previewimg.Width, previewimg.Height));
pictureBox2.DrawToBitmap(bmp, new Rectangle(pictureBox2.Location.X - previewimg.Location.X, pictureBox2.Location.Y - previewimg.Location.Y, pictureBox2.Width, pictureBox2.Height));
bmp.Save(#"C:\Fuepass\output.jpg", System.Drawing.Imaging.ImageFormat.Jpeg);
MessageBox.Show("Saved,Locaiton : C:\\Fuepass\\");
// SaveFileDialog dialog = new SaveFileDialog();
// dialog.Filter = "JPG(*.JPG)|*.jpg";
// if (dialog.ShowDialog() == DialogResult.OK)
// {
// previewimg.Image.Save(dialog.FileName);
// pictureBox2.Image.Save(dialog.FileName);
// }
// }
}
private void PictureBoxLoad_Click(object sender, EventArgs e)
{
}
private void PictureBoxLoad_MouseDown_1(object sender, MouseEventArgs e)
{
PictureBoxLoad.Invalidate();
xDown = e.X;
yDown = e.Y;
crop.Enabled = true;
}
private void PictureBoxLoad_MouseUp_1(object sender, MouseEventArgs e)
{
//pictureBox1.Image.Clone();
xUp = e.X;
yUp = e.Y;
Rectangle rec = new Rectangle(xDown, yDown, Math.Abs(xUp - xDown), Math.Abs(yUp - yDown));
using (Pen pen = new Pen(Color.YellowGreen, 3))
{
PictureBoxLoad.CreateGraphics().DrawRectangle(pen, rec);
}
rectCropArea = rec;
crop.Enabled = true;
}
private void crop_Click_1(object sender, EventArgs e)
{
try
{
pictureBox2.Refresh();
//Prepare a new Bitmap on which the cropped image will be drawn
Bitmap sourceBitmap = new Bitmap(PictureBoxLoad.Image, PictureBoxLoad.Width, PictureBoxLoad.Height);
Graphics g = pictureBox2.CreateGraphics();
//Draw the image on the Graphics object with the new dimesions
g.DrawImage(sourceBitmap, new Rectangle(0, 0, pictureBox2.Width, pictureBox2.Height), rectCropArea, GraphicsUnit.Pixel);
sourceBitmap.Dispose();
crop.Enabled = false;
var path = Environment.CurrentDirectory.ToString();
ms = new System.IO.MemoryStream();
//pictureBox2.Image.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
byte[] ar = new byte[ms.Length];
var timeout = ms.WriteAsync(ar, 0, ar.Length);
}
catch (Exception ex)
{
}
if (pictureBox2.Image == null)
{
MessageBox.Show("no image");
}
}
}
}
plz tell me the error
You should be able to set the Image to a Bitmap. But do not dispose the Bitmap before you do the save. Hope this helps.
private void crop_Click_1(object sender, EventArgs e)
{
try
{
pictureBox2.Refresh();
//Prepare a new Bitmap on which the cropped image will be drawn
Bitmap sourceBitmap = new Bitmap(PictureBoxLoad.Image, PictureBoxLoad.Width, PictureBoxLoad.Height);
Graphics g = pictureBox2.CreateGraphics();
//Draw the image on the Graphics object with the new dimesions
g.DrawImage(sourceBitmap, new Rectangle(0, 0, pictureBox2.Width, pictureBox2.Height), rectCropArea, GraphicsUnit.Pixel);
crop.Enabled = false;
var path = Environment.CurrentDirectory.ToString();
ms = new System.IO.MemoryStream();
pictureBox2.Image = sourceBitmap;
pictureBox2.Image.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
byte[] ar = new byte[ms.Length];
var timeout = ms.WriteAsync(ar, 0, ar.Length);
sourceBitmap.Dispose();
}
catch (Exception ex)
{
}
if (pictureBox2.Image == null)
{
MessageBox.Show("no image");
}
}
Related
In my form. I have two picturebox and a button that capture the image into picturebox.
Two Picturebox
WebcamImage - represent the live camera image
PreviewImage - represent the Captured image from webcamimage
When i saved this captured image it will go to my UserImage picturebox (In my Usercontrol)
The problems is i don't know how i'm gonna get the picturebox image path.
What i want is when i click my saved button the image path will be saved to my label text.
Here's my code
PS: I'm using Aforge.dll
public partial class CaptureImage : Form
{
private FilterInfoCollection CaptureDevice;
private VideoCaptureDevice FinalFrame;
RegisterCustomer _view;
public CaptureImage(RegisterCustomer view)
{
InitializeComponent();
this._view = view;
}
private void CaptureImage_Load(object sender, EventArgs e)
{
CaptureDevice = new FilterInfoCollection(FilterCategory.VideoInputDevice);
foreach (FilterInfo Device in CaptureDevice)
{
comboBox1.Items.Add(Device.Name);
}
comboBox1.SelectedIndex = 0;
FinalFrame = new VideoCaptureDevice();
FinalFrame = new VideoCaptureDevice(CaptureDevice[comboBox1.SelectedIndex].MonikerString);
if (FinalFrame.VideoCapabilities.Length > 0)
{
string highestSolution = "0;0";
//Search for the highest resolution
for (int i = 0; i < FinalFrame.VideoCapabilities.Length; i++)
{
if (FinalFrame.VideoCapabilities[i].FrameSize.Width > Convert.ToInt32(highestSolution.Split(';')[0]))
highestSolution = FinalFrame.VideoCapabilities[i].FrameSize.Width.ToString() + ";" + i.ToString();
}
}
FinalFrame.NewFrame += new NewFrameEventHandler(FinalFrame_NewFrame);
FinalFrame.Start();
btn_save.Hide();
btn_cancel.Hide();
}
void FinalFrame_NewFrame(object sender, NewFrameEventArgs eventArgs)
{
WebcamImage.Image = (Bitmap)eventArgs.Frame.Clone();
}
private void CaptureImage_FormClosing(object sender, FormClosingEventArgs e)
{
if (FinalFrame.IsRunning == true)
{
FinalFrame.Stop();
}
}
private void btn_save_Click(object sender, EventArgs e)
{
_view.UserImage.Image = PreviewImage.Image;
this.Close();
}
private void btn_cancel_Click(object sender, EventArgs e)
{
this.Close();
}
private void btn_capture_Click(object sender, EventArgs e)
{
PreviewImage.Image = (Bitmap)WebcamImage.Image.Clone();
PreviewImage.BringToFront();
btn_capture.Hide();
btn_save.Show();
btn_cancel.Show();
}
}
This is only i know in getting the picturebox image path by using openfile dialog
using (OpenFileDialog ofd = new OpenFileDialog())
{
ofd.Filter = "Image Files (*.jpg;*.jpeg;.*.png; | *.jpg;*.jpeg;.*.png;)";
ofd.FilterIndex = 1;
ofd.Multiselect = false;
ofd.Title = "Select Image File";
if (ofd.ShowDialog() == DialogResult.OK)
{
location = ofd.FileName;
path.Text = location;
UserImage.Image = Image.FromFile(location);
UserImage.SizeMode = PictureBoxSizeMode.StretchImage;
}
}
I am trying to develop a WindowsForm Application which will use webcamera to detect QRCode and decode the message. For this I am using AForge.NET and ZXing.NET.
So far, I have been able to figure out how to decode the QRCode from an URI, but I want to detect the QRCode from webcamera, and decode it.
Below is the sample to my code.
public String Decode(Uri uri)
{
Bitmap image;
try
{
image = (Bitmap)Bitmap.FromFile(uri.LocalPath);
}
catch (Exception ex)
{
throw new FileNotFoundException("Resource not found: " + uri);
}
using (image)
{
String text = "";
LuminanceSource source = new BitmapLuminanceSource(image);
BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source));
Result result = new MultiFormatReader().decode(bitmap);
if (result != null)
{
text = result.Text;
return text;
}
text = "Provided QR couldn't be read.";
return text;
}
}
private FilterInfoCollection videoDevices;
private VideoCaptureDevice videoSource;
private Bitmap capturedImage;
private String message = "";
public FormQRCodeScanner()
{
InitializeComponent();
}
private void FormQRCodeScanner_Load(object sender, EventArgs e)
{
videoDevices = new FilterInfoCollection(FilterCategory.VideoInputDevice);
foreach (FilterInfo device in videoDevices)
{
comboBoxCameraSource.Items.Add(device.Name);
}
comboBoxCameraSource.SelectedIndex = 0;
videoSource = new VideoCaptureDevice();
buttonStartStop.Text = "Start";
buttonCapture.Enabled = false;
buttonDecode.Enabled = false;
}
private void FormQRCodeScanner_FormClosing(object sender, FormClosingEventArgs e)
{
if (videoSource.IsRunning)
{
videoSource.Stop();
}
}
void videoSource_NewFrame(object sender, NewFrameEventArgs eventArgs)
{
Bitmap image = (Bitmap) eventArgs.Frame.Clone();
pictureBoxSource.Image = image;
}
private void buttonStartStop_Click(object sender, EventArgs e)
{
if (videoSource.IsRunning)
{
videoSource.Stop();
pictureBoxSource.Image = null;
pictureBoxCaptured.Image = null;
pictureBoxSource.Invalidate();
pictureBoxCaptured.Invalidate();
buttonStartStop.Text = "Start";
buttonCapture.Enabled = false;
buttonDecode.Enabled = false;
}
else
{
videoSource = new VideoCaptureDevice(videoDevices[comboBoxCameraSource.SelectedIndex].MonikerString);
videoSource.NewFrame += new NewFrameEventHandler(videoSource_NewFrame);
videoSource.Start();
buttonStartStop.Text = "Stop";
buttonCapture.Enabled = true;
buttonDecode.Enabled = true;
}
}
private void buttonCapture_Click(object sender, EventArgs e)
{
if (videoSource.IsRunning)
{
pictureBoxCaptured.Image = (Bitmap)pictureBoxSource.Image.Clone();
capturedImage = (Bitmap)pictureBoxCaptured.Image;
}
}
private void buttonDecode_Click(object sender, EventArgs e)
{
if (capturedImage != null)
{
ExtractQRCodeMessageFromImage(capturedImage);
richTextBoxMessage.Text = message;
richTextBoxMessage.ReadOnly = true;
}
}
private string ExtractQRCodeMessageFromImage(Bitmap bitmap)
{
try
{
BarcodeReader reader = new BarcodeReader
(null, newbitmap => new BitmapLuminanceSource(bitmap), luminance => new GlobalHistogramBinarizer(luminance));
reader.AutoRotate = true;
reader.TryInverted = true;
reader.Options = new DecodingOptions { TryHarder = true };
var result = reader.Decode(bitmap);
if (result != null)
{
message = result.Text;
return message;
}
else
{
message = "QRCode couldn't be decoded.";
return message;
}
}
catch (Exception ex)
{
message = "QRCode couldn't be detected.";
return message;
}
}
**For this you should install these packages
Install-Package AForge
Install-Package AForge.Video
Install-Package AForge.Video.DirectShow
Install-Package ZXing.Net
you can watch this video for more help
https://www.youtube.com/watch?v=wcoy0Gwxr50**
using System.IO;
using AForge;
using AForge.Video;
using AForge.Video.DirectShow;
using ZXing;
using ZXing.Aztec;
private void Form1_Load(object sender, EventArgs e)
{
CaptureDevice = new FilterInfoCollection(FilterCategory.VideoInputDevice);
foreach (FilterInfo Device in CaptureDevice)
{
comboBox1.Items.Add(Device.Name);
}
comboBox1.SelectedIndex = 0;
FinalFrame = new VideoCaptureDevice();
}
private void button1_Click(object sender, EventArgs e)
{
FinalFrame = new VideoCaptureDevice(CaptureDevice[comboBox1.SelectedIndex].MonikerString);
FinalFrame.NewFrame += new NewFrameEventHandler(FinalFrame_NewFrame);
FinalFrame.Start();
}
private void FinalFrame_NewFrame(object sender, NewFrameEventArgs eventArgs)
{
pictureBox1.Image = (Bitmap)eventArgs.Frame.Clone();
}
private void timer1_Tick(object sender, EventArgs e)
{
BarcodeReader Reader = new BarcodeReader();
Result result = Reader.Decode((Bitmap)pictureBox1.Image);
try
{
string decoded = result.ToString().Trim();
if (decoded != "")
{
timer1.Stop();
MessageBox.Show(decoded);
Form2 form = new Form2();
form.Show();
this.Hide();
}
}
catch(Exception ex){
}
}
private void button2_Click(object sender, EventArgs e)
{
timer1.Enabled = true;
timer1.Start();
}
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
if (FinalFrame.IsRunning == true)
{
FinalFrame.Stop();
}
}
I'm using the AForge.NET library (http://www.aforgenet.com) to capture an image from my webcam,show it in a picturebox and then save it.But the capture is not like mirror. Does anybody know how to mirror the capture in c#?
public static Bitmap _latestFrame;
private FilterInfoCollection webcam;
private VideoCaptureDevice cam;
Bitmap bitmap;
private int orderidcapture = 0;
private string date1 = "";
private void Frm_Capturet_Load(object sender, EventArgs e)
{
try
{
piclocation = new Ini(Application.StartupPath + "\\UserSetting.ini").GetValue("Webservice",
"DigitalSign").ToString();
webcam = new FilterInfoCollection(FilterCategory.VideoInputDevice);
foreach (FilterInfo VideoCaptureDevice in webcam)
{
comboBox1.Items.Add(VideoCaptureDevice.Name);
}
comboBox1.SelectedIndex = 0;
}
catch (Exception error)
{
MessageBox.Show(error.Message + "error11");
}
Focus();
}
private string piclocation = "";
void cam_NewFrame(object sender, NewFrameEventArgs eventArgs)
{
bitmap = (Bitmap)eventArgs.Frame.Clone();
picFrame.Image = bitmap;
}
private void button1_Click(object sender, EventArgs e)
{
cam = new VideoCaptureDevice(webcam[comboBox1.SelectedIndex].MonikerString);
cam.NewFrame += new NewFrameEventHandler(cam_NewFrame);
cam.DisplayPropertyPage(new IntPtr(0));
cam.Start();
}
private void button2_Click(object sender, EventArgs e)
{
date1 = date1.Replace("/", "");
Bitmap current = (Bitmap)bitmap.Clone();
string filepath = Environment.CurrentDirectory;
string fileName = System.IO.Path.Combine(piclocation, orderidcapture + "__" + date1 + #"name.jpg");
current.Save(fileName, System.Drawing.Imaging.ImageFormat.Jpeg);
current.Dispose();
current = null;
}
solved the problem by my own.
void cam_NewFrame(object sender, NewFrameEventArgs eventArgs)
{
try
{
bitmap = (Bitmap)eventArgs.Frame.Clone();
///add these two lines to mirror the image
var filter = new Mirror(false, true);
filter.ApplyInPlace(bitmap);
///
picFrame.Image = bitmap;
}
catch
{
}
}
I have some problems about savefiledialog c#, I have an unhandled exception of type System.NullReferenceException when I debug, this's code:
private void saveToolStripMenuItem_Click(object sender, System.EventArgs e)
{
switch (fileName)
{
case "":
{
saveFileDialog1 = new SaveFileDialog
{
Filter = #"Image files (*.bmp)|*.bmp|All files (*.*)|*.*",
FileName = "MyPicture.bmp"
};
if (saveFileDialog1.ShowDialog() != DialogResult.OK) return;
fileName = saveFileDialog1.FileName;
bitmap.Save(saveFileDialog1.FileName, ImageFormat.Bmp);
}
break;
default:
{
bitmap.Save(fileName, ImageFormat.Bmp);
}
break;
}
}
here is my declare:
private string fileName = "";
private Bitmap bitmap;
private Bitmap curBitmap;
here is my full code:
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
//Bitmap
//Graphics
Graphics g;
Pen p = new Pen(Color.Black, 8);
Point start = new Point(0, 0);
Point end = new Point(0, 0);
bool drawing = false;
//private int x1;
//private int x2;
//private int y1;
//private int y2;
//private int d1;
//private int d2;
private string fileName = "";
private Bitmap bitmap;
private Bitmap curBitmap;
private Size fullSize;
private void btnColorPicker_Click(object sender, EventArgs e)
{
//Get colors from colordialog
DialogResult r = colorDialog1.ShowDialog();
if (r == DialogResult.OK)
{
p.Color = colorDialog1.Color;
}
}
private void PanelDrawing_MouseUp(object sender, MouseEventArgs e)
{
drawing = false;
}
private void PanelDrawing_MouseMove(object sender, MouseEventArgs e)
{
if (drawing && !earaser)
{
p.Width = PenSize.Value;
p.Color = colorDialog1.Color;
end = e.Location;
g = PanelDrawing.CreateGraphics();
g.DrawLine(p, start, end);
PanelDrawing.Cursor = Cursors.HSplit;
}
else if (drawing && earaser)
{
end = e.Location;
g = PanelDrawing.CreateGraphics();
g.DrawLine(p, start, end);
PanelDrawing.Cursor = Cursors.Cross;
}
else if (!drawing)
{
PanelDrawing.Cursor = Cursors.Default;
}
start = end;
}
private void PanelDrawing_MouseDown(object sender, MouseEventArgs e)
{
start = e.Location;
if (e.Button == MouseButtons.Left)
{
drawing = true;
}
}
private void PenSize_Scroll(object sender, EventArgs e)
{
p.Width = PenSize.Value;
label1.Text = "" + PenSize.Value;
}
bool earaser = false;
private void btnEaraser_Click(object sender, EventArgs e)
{
p.Color = Color.White;
p.Width = 10;
earaser = true;
}
private void btnBrush_Click(object sender, EventArgs e)
{
earaser = false;
}
private void btnClear_Click(object sender, EventArgs e)
{
g.Clear(PanelDrawing.BackColor);
}
private void saveToolStripMenuItem_Click(object sender, System.EventArgs e)
{
if (string.IsNullOrWhiteSpace(fileName))
{
saveFileDialog1 = new SaveFileDialog
{
Filter = #"Image files (*.bmp)|*.bmp|All files (*.*)|*.*",
FileName = "MyPicture.bmp"
};
if (saveFileDialog1.ShowDialog() != DialogResult.OK)
return;
fileName = saveFileDialog1.FileName;
bitmap.Save(saveFileDialog1.FileName, ImageFormat.Bmp);
}
else
{
bitmap.Save(fileName, ImageFormat.Bmp);
}
}
private void Form1_Load(object sender, EventArgs e)
{
fullSize = SystemInformation.PrimaryMonitorMaximizedWindowSize;
bitmap = new Bitmap(fullSize.Width, fullSize.Height);
g = Graphics.FromImage(bitmap);
g.SmoothingMode = SmoothingMode.AntiAlias;
g.Clear(BackColor);
}
}
probably it didn't catch the variable if its null or an empty string.
so instead of using switch statement, try doing it in If-Else statement.
This isn't the place to use a switch statement. This is much easier re-written as an if:
private void saveToolStripMenuItem_Click(object sender, System.EventArgs e)
{
if (string.IsNullOrWhiteSpace(fileName))
{
saveFileDialog1 = new SaveFileDialog
{
Filter = #"Image files (*.bmp)|*.bmp|All files (*.*)|*.*",
FileName = "MyPicture.bmp"
};
if (saveFileDialog1.ShowDialog() != DialogResult.OK)
return;
fileName = saveFileDialog1.FileName;
bitmap.Save(saveFileDialog1.FileName, ImageFormat.Bmp);
}
else
{
bitmap.Save(fileName, ImageFormat.Bmp);
}
}
The switch isn't appropriate just because its extremely confusing, and you have to test for multiple cases (null, empty string, whitespace). You can jam the code and make it work, but this is a lot more fool-proof.
Without seeing the rest of your code, its impossible to tell whether bitmap is going to be null or not. If its null, then calling .Save will result in a NullReferenceException. The best way to know why its null is to learn how to use the debugger. Set a breakpoint at the bitmap or where you utilize the bitmap to see why you aren't writing to it or creating the object in the first place.
Since you haven't specified "where" the System.NullReferenceException is taking place. I will assume the following 2 cases
1.fileName is null. If that's the case add 1 more case (as shown below ) to your switch statement that takes null into consideration.
switch (fileName)
{
case "":
case null:
{
saveFileDialog1 = new SaveFileDialog
{
Filter = #"Image files (*.bmp)|*.bmp|All files (*.*)|*.*",
FileName = "MyPicture.bmp"
};
if (saveFileDialog1.ShowDialog() != DialogResult.OK) return;
fileName = saveFileDialog1.FileName;
bitmap.Save(saveFileDialog1.FileName, ImageFormat.Bmp);
}
break;
default:
{
bitmap.Save(fileName, ImageFormat.Bmp);
}
break;
}
2. You are using the same image stream, while saving, which was used to construct it. If that's the case use a new bitmap object as shown below.
var newBitmap = new Bitmap(bitmap);
switch (fileName)
{
case "":
case null:
{
saveFileDialog1 = new SaveFileDialog
{
Filter = #"Image files (*.bmp)|*.bmp|All files (*.*)|*.*",
FileName = "MyPicture.bmp"
};
if (saveFileDialog1.ShowDialog() != DialogResult.OK) return;
fileName = saveFileDialog1.FileName;
newBitmap.Save(saveFileDialog1.FileName, ImageFormat.Bmp);
}
break;
default:
{
newBitmap.Save(fileName, ImageFormat.Bmp);
}
break;
}
Firstly, switch is not good way to handle strings I think.
string.IsNullorEmpty and string.IsNullorWhiteSpace might be useful for you.
Can you trace bitmap on your console? Are you sure you declared and initialized it correctly in your code?
This should solve any possibility:
private void saveToolStripMenuItem_Click(object sender,System.EventArgs e)
{
var _Bitmap = new Bitmap(bitmap);
//when we quit here we don't need this anymore; declaring it here helps with memory management
if(_Bitmap == null)
return;
if(string.IsNullorEmpty(fileName)||string.IsNullorWhiteSpace(fileName)
{
Filter = #"Image files (*.bmp)|*.bmp|All files (*.*)|*.*",
FileName = "MyPicture.bmp"
}
else
{
_Bitmap.Save(fileName,ImageFormat.Bmp);
}
}
You assign bitmap on Form1_Load, try to do it on separate method and call it when you need it.
I have this problem when I drag to select region of the image in the picturebox more than two times and run the scanning. This is an OCR system.
region OCR(Tab4_Component)
//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;
area.Save(#"C:\Users\Shen\Desktop\LenzOCR\TempFolder\tempPic.jpg");
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
i understand the reason it occur is that the image has been duplicated. But I have no idea how to solve it.
First off this looks like a dublicate of this topic:
c# Bitmap.Save A generic error occurred in GDI+ windows application
You also authored that question. From what I can tell it's the same question regarding the same code.
You mention this happens the second time you select an area, and both time you save the image to the same path. You also say the errors occurs when saving.
I think that would be a very strong indication of a permission error. Have you tried saving to a new file name every time as a test?
If it's a permission error then you simply need to dispose of any resources that have taken a lock on that file.
There are plenty of examples of this out there:
http://www.kerrywong.com/2007/11/15/understanding-a-generic-error-occurred-in-gdi-error/
public void Method1()
{
Image img = Image.FromFile(fileName);
Bitmap bmp = img as Bitmap;
Graphics g = Graphics.FromImage(bmp);
Bitmap bmpNew = new Bitmap(bmp);
g.DrawImage(bmpNew, new Point(0, 0));
g.Dispose();
bmp.Dispose();
img.Dispose();
//code to manipulate bmpNew goes here.
bmpNew.Save(fileName);
}
There could however be other issues. If you get the image from a stream, this stream needs to remain open until you're done with the image. (When you dispose of the image you'll automatically dispose of the stream.)
I can't see anything like that in the code you've posted though.
If you are using a 3rd party library for the OCR part, it could also have taken a lock on the resource.
A good place to read about this would be here:
http://support.microsoft.com/?id=814675
However from all you've said it simply sounds like there's a lock on the file you try to save to. So as mentioned above I would start off by simply trying to give the file a new name each time. If it doesn't work then you can start exploring other possibilities.
Quick and dirty example:
area.Save(#"C:\Users\Shen\Desktop\LenzOCR\TempFolder\tempPic-" + Guid.NewGuid().ToString() + #".jpg");
You should try this before dismissing a permission issue.