Close a file which is in use from a PictureBox - c#

I'm using this code for converting Excel to image and preview it in a picturebox.
The code is working for first time. But when i'm trying to upload second time i get an error that says that the image file is in use.specically in save point.
OpenFileDialog openFileDialog1 = new OpenFileDialog();
openFileDialog1.Filter = "bak files (*.xls)|*.xls|All files (*.*)|*.*";
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
Img1 = openFileDialog1.FileName;
//Create a new Workbook object and
//Open a template Excel file.
Workbook book = new Workbook(Img1);
//Get the first worksheet.
Worksheet sheet = book.Worksheets[0];
//Define ImageOrPrintOptions
ImageOrPrintOptions imgOptions = new ImageOrPrintOptions();
//Specify the image format
imgOptions.ImageFormat = System.Drawing.Imaging.ImageFormat.Jpeg;
//Only one page for the whole sheet would be rendered
imgOptions.OnePagePerSheet = true;
//Render the sheet with respect to specified image/print options
SheetRender sr = new SheetRender(sheet, imgOptions);
//Render the image for the sheet
Bitmap bitmap = sr.ToImage(0);
//Save the image file specifying its image format.
bitmap.Save("C:\\1.jpg");\\in this point i get my error that it says general error GDI+.
pictureBox2.Image = Image.FromFile("C:\\1.jpg");
pictureBox2.SizeMode = PictureBoxSizeMode.StretchImage;
}
else
{
this.DialogResult = DialogResult.None;
}
}
I thing i must stop first use from my picturebox preview and then to upload again. But how will i do that? I tried
pictureBox1.Image=null
,but it didnt worked.

When you use
pictureBox2.Image = Image.FromFile("C:\\1.jpg");
The static call keeps the file open (and locked). So you can't overwrite the file.
Solution:
if (pictureBox2.Image != null) pictureBox2.Image.Dispose();
bitmap.Save("C:\\1.jpg");
bitmap.Dispose();
pictureBox2.Image = new Bitmap(Image.FromFile("C:\\1.jpg"));
This way the file is released and can later be overwritten.
An alternative:
if (pictureBox2.Image != null) pictureBox2.Image.Dispose();
bitmap.Save("C:\\1.jpg");
bitmap.Dispose();
using (Bitmap bm = new Bitmap(C:\\1.jpg"))
{
pictureBox2.Image = new Bitmap(bm);
};

I solved this using FileStream.
Dim fs1 As System.IO.FileStream
fs1 = New System.IO.FileStream(Bitmap, IO.FileMode.Open, IO.FileAccess.Read)
PictureBox1.Image = System.Drawing.Image.FromStream(fs1)
fs1.Close()
Look that you should fs1.close() to finish the stream.
The FileStream Class represents a File in the machine. FileStream allows to move data to and from the stream as arrays of bytes. It means, it does'nt works directly in the file, just as a Stream that you can manipulate.
The code is in vb.net (because it works for me).
So there will be no problem translating it to C #

Here VB.NET Example for opening Image in picture box without keeping file locked for other operation.
VB.NET Code.
Dim fs As System.IO.FileStream
' Specify a valid picture file path on your computer.
fs = New System.IO.FileStream("C:\WINNT\Web\Wallpaper\Fly Away.jpg",
IO.FileMode.Open, IO.FileAccess.Read)
PictureBox1.Image = System.Drawing.Image.FromStream(fs)
fs.Close()
C# Code.
System.IO.FileStream fs;
// Specify a valid picture file path on your computer.
fs = new System.IO.FileStream(#"C:\WINNT\Web\Wallpaper\Fly Away.jpg", System.IO.FileMode.Open, System.IO.FileAccess.Read);
PictureBox1.Image = System.Drawing.Image.FromStream(fs);
fs.Close();
Reference -
https://www.codeproject.com/Questions/492654/5bc-23-5dplusdeleteplusimagepluswhichplusisplusope

Related

How to reduce Image size before uploading to SQL server

I am trying to reduce employee picture before uploading. checked for help but the all the answers are very much confusing. And I am here to ask help from experts :)
I am opening image to my picture box through below code
OpenFileDialog dlg = new OpenFileDialog();
dlg.Filter = "JPG Files(*.jpg)|*.jpg|GIF Files(*.gif)|*.gif|All Files(*.*)|*.*";
dlg.Title = "Select Employee Picture";
if (dlg.ShowDialog() == DialogResult.OK)
{
Image im = new Bitmap(dlg.FileName);
picEMP.Image = im;
string imgloc = dlg.FileName.ToString();
}
and making the image to binary with below codes
byte[] img = null;
FileStream fs = new FileStream(imgloc, FileMode.Open, FileAccess.Read);
BinaryReader br = new BinaryReader(fs);
img = br.ReadBytes((int)fs.Length);
and finally uploading with a parameter value
command.Parameters.Add(new SqlParameter("#img", img));
But I am not checking image size. I want to check the image size or the resolution(height, width) and reducing image size with a fix size like (188,222) and then upload image to my sql server. My SQL connection code is below:
SqlConnection conn = new SqlConnection("Data Source=host; Initial Catalog=TimeAttendance; User ID=id; Password=password");
Please Help .......
Have you tried zipping it up and compressing it. The below library should work pretty well for that.
http://dotnetzip.codeplex.com/

how to set picturebox image location from zip without extrat?

I want to set picture box from zip file without extract zip.
my code:
ZipFile zip = new ZipFile("data.zip");
using (Stream s = zip["p3.png"].OpenReader())
{
picturebox.ImageLocation = s.ToString();
}
Picture Box Show error image.
I should use Bitmap. Correct Code:
ZipFile zip = new ZipFile("data.zip");
using (Stream s = zip["p3.png"].OpenReader())
{
Bitmap bitmap= new Bitmap(s);
PictureBox picturebox.Image = bitmap;
}

How to read image dimensions at C# wpf - there is no dispose method for BitmapImage

With the way below i am able to read.
But there is no dispose method so i am not able to delete the file later.
So the below method is getting failed.
I could not come up with a proper solution.
Bitmap class is not recognized in C# 4.5 WPF application.
thank you
DirectoryInfo dInfo = new DirectoryInfo(#"C:\pokemon_files\images\");
FileInfo[] subFiles = dInfo.GetFiles();
BitmapImage myImg;
foreach (var vrImage in subFiles)
{
string srFilePath = vrImage.FullName;
System.Uri myUri = new Uri(srFilePath);
myImg = new BitmapImage(myUri);
if (myImg.Width < 50)
{
File.Delete(srFilePath);
continue;
}
}
I assume the error you get is caused by trying to delete the file which is currently in use
by the bitmap (I don't remember the exception name).
There is a solution to that, that is: making a byte stream.
byte[] imageData;
using(var fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read))
using(var binaryReader = new BinaryReader(fileStream))
{
imageData = binaryReader.ReadBytes((int)fileStream.Length);
}
var bitmap = new BitmapImage();
bitmap.BeginInit();
bitmap.StreamSource = new MemoryStream(imageData);
bitmap.EndInit();
//Now you can check the width & height, the file stream should be closed so you can
//delete the file.
[EDIT]
If you don't want to read the bytes by BinaryReader, there's always this solution if you want to read all bytes from the file.

How to add PNG and JPG at runtime

I am using C# and WPF. I want to add a PNG and JPG at runtıme to an image source but I get an exception that says:
Can not implicitly add convert type string to Sytem.Windows.Media.imageSource
using System.IO; //for : input - output
using Microsoft.Win32; //For : OpenFileDialog / SaveFileDialog
using System.Windows.Media.Imaging; //For : BitmapImage etc etc
<Image x:Name="img" Margin="9,13.5,6,0.5" Source="Laugh.ico">
private void ac(object sender, RoutedEventArgs args)
{
OpenFileDialog dlg = new OpenFileDialog();
// Configure open file dialog box
dlg.FileName = "Document"; // Default file name
dlg.DefaultExt = ".PNG"; // Default file extension
dlg.Filter = " (.PNG)|*.PNG"; // Filter files by extension
// Show open file dialog box
Nullable<bool> result = dlg.ShowDialog();
// Process open file dialog box results
if (result == true)
{
// Open document
string filename = dlg.FileName;
img.Source=filename;
}
}
Sorry but as you might have noticed, that code wonT even compile. You cannot set the image source as the filename
img.Source = filename
Have a look at the reference.
Try this:
img.Source = new BitmapImage(new Uri(filename));
Not sure if this will work for an image outside of the program, but you can try:
Uri uri = new Uri(dlg.File.FullName, UriKind.RelativeOrAbsolute);
ImageSource imgSource = new BitmapImage(uri);
img.Source = imgSource;
I think the key line is:
img.Source=filename
which should be something like:
BitmapImage bi= new BitmapImage();
bi.BeginInit();
bi.UriSource = new Uri(filename, UriKind.Relative);
bi.EndInit();
img.Source = bi;
As you have to actually read the image file in from disk.

Read the entire file into a byte array in WINFORMS

I want to read the content of the file opened using file dialog box and then save it in a byte array to pass it to a web service
Stream myStream;
OpenFileDialog saveFileDialog1 = new OpenFileDialog();
saveFileDialog1.Filter = "zip files (*.zip)|*.zip|All files (*.*)|*.*";
saveFileDialog1.FilterIndex = 2;
saveFileDialog1.RestoreDirectory = true;
if (saveFileDialog1.ShowDialog() == DialogResult.OK)
{
if ((myStream = saveFileDialog1.OpenFile()) != null)
{
NSITESERVICE.UploadSoapClient obj = new NSITESERVICE.UploadSoapClient();
byte[] filebytes = //what should i pass it over here...
obj.UploadFile("kamal", "p#ssword", filebytes);
// Code to write the stream goes here.
myStream.Close();
}
}
I dont know where i am wrong
Any help is appreciated. Thnaks
You are not assigning anything to filebytes variable so you are essentially passing null to the service. Use File.ReadAllBytes method to read all the bytes and pass it to the webservice.
You're not actually reading the bytes out of the myStream.
byte[] fileBytes = new byte[myStream.Length];
myStream.Read(fileBytes,0,mystream.Length);
obj.UploadFile(...)

Categories

Resources