C# how to use variable outside of block of code - c#

I have the following code. I want to use pictureBox1.Image = image outside of the code block like so:
private void button1_Click(object sender, EventArgs e) {
using(MemoryStream memoryStream = new MemoryStream()) {
pic.Image.Save(memoryStream, System.Drawing.Imaging.ImageFormat.Bmp);
byte[] imageBytes = memoryStream.ToArray();
}
Image image = Image.FromStream(memoryStream);
pictureBox1.Image = image;
}
I get the folloowing error: The name 'memoryStream' does not exist in the current context. I know I can do the following move the last 2 lines into the brackets and the code works but How can I use variable outside of the { } block of code
I know the code below works but i just want to know if there is a way to use pictureBox1.Image = image outside of the block of code.
private void button1_Click(object sender, EventArgs e)
{
using(MemoryStream memoryStream = new MemoryStream())
{
pic.Image.Save(memoryStream, System.Drawing.Imaging.ImageFormat.Bmp);
byte[] imageBytes = memoryStream.ToArray();
Image image = Image.FromStream(memoryStream);
pictureBox1.Image = image;
}
}

You can't and shouldn't use the stream outside of the using scope, after that it will get disposed and you don't run into leaking issues.
You could just assign the value after the scope, when you declare the variable before it.
private void button1_Click(object sender, EventArgs e)
{
Image image;
using(MemoryStream memoryStream = new MemoryStream())
{
pic.Image.Save(memoryStream, System.Drawing.Imaging.ImageFormat.Bmp);
// byte[] imageBytes = memoryStream.ToArray(); //unused?
image = Image.FromStream(memoryStream);
}
pictureBox1.Image = image;
}
Or better yet make a function to read the image and return it.
private void button1_Click(object sender, EventArgs e)
{
pictureBox1.Image = readImage();
}
private Image readImage()
{
using(MemoryStream memoryStream = new MemoryStream())
{
pic.Image.Save(memoryStream, System.Drawing.Imaging.ImageFormat.Bmp);
// byte[] imageBytes = memoryStream.ToArray(); //unused?
return Image.FromStream(memoryStream);
}
}

There's no problem putting that line outside the using block. The problem is line before. You can't use memoryStream outside the using block. The whole point of the using block is to create a scope for that variable and ensure that the object assigned to it is disposed at the end of the block. You can do this:
private void button1_Click(object sender, EventArgs e) {
Image image;
using(MemoryStream memoryStream = new MemoryStream()) {
pic.Image.Save(memoryStream, System.Drawing.Imaging.ImageFormat.Bmp);
byte[] imageBytes = memoryStream.ToArray();
image = Image.FromStream(memoryStream);
}
pictureBox1.Image = image;
}

You can define MemoryStream outside the code block:
MemoryStream memoryStream = new MemoryStream();
using (memoryStream)
{
pic.Image.Save(memoryStream, System.Drawing.Imaging.ImageFormat.Bmp);
byte[] imageBytes = memoryStream.ToArray();
}
Image image = Image.FromStream(memoryStream);
pictureBox1.Image = image;
Edit:(just for test)
If you think using releases all resources for the variable defined outside, test the following code:
MemoryStream memoryStream = new MemoryStream();
using (memoryStream)
{
byte[] messageBytes = Encoding.ASCII.GetBytes("test Massage");
memoryStream.Write(messageBytes, 0, messageBytes.Length);
}
var data = Encoding.Default.GetString(memoryStream.ToArray()); // data = "test Massage"

Related

Accessing Picturebox From Stream

How can I access picturebox1 from my ocr.Image = img bit of the code. I have it working if I load it by using
ocr.Image = ImageStream.FromFile("C:/Users/John/Pictures/3.jpg"); // Give the image to the library
but obviously thats not what I am tryng to achive.
Error is:
cannot implicitly convert type system.drawing.image to
apose.ocr.iimagestream
private void timer1_Tick(object sender, EventArgs e)
{
//SendKeys.Send("{PRTSC}");
Image img = Clipboard.GetImage();
pictureBox1.Image = img;
//ocr processing
ocr.Image = img; // Give the image to the library
if (ocr.Process()) // Start processing it
{
label1.Text = "Text: " + ocr.Text;
}
}
Try this:
if(img!=null)
{
var ms = new MemoryStream();
img.Save(ms, ImageFormat.Jpeg); // put here the image format
ms.Position = 0;
ocr.Image = ImageStream.FromStream(ms,ImageStreamFormat.Jpg);
..
..//all your processing stuff
}

cast image from stream

am using the cell click event for data grid view, and am finding problems trying to cast image from stream
private void abaanaCCDataGridView_CellClick(object sender, DataGridViewCellEventArgs e)
{
this.Ptxtspn_code.Text = this.abaanaCCDataGridView.SelectedRows[0].Cells[this.dataGridViewTextBoxColumn2.Name].Value.ToString();
//this.PtxtFname.Text
this.abaanaCCTableAdapter.Fill(this.abaanaDataSet.abaanaCC);
byte[] mydata = (byte[])this.abaanaDataSet.abaanaCC.Rows[0]["CCImage"];
//byte[] mydata = (byte[])this.abaanaCCDataGridView.SelectedRows[0].Cells[this.dataGridViewImageColumn1.Name];
MemoryStream stream = new MemoryStream(mydata);
//Image img = Image.FromStream(stream);
this.PpicBox.Image = (Image.FromStream(stream))abaanaCCDataGridView.SelectedRows[0].Cells[this.dataGridViewImageColumn1.Name].Value;
}
That line makes no sense:
(Image.FromStream(stream)abaanaCCDataGridView.SelectedRows[0].Cells[this.dataGridViewImageColumn1.Name].Value
I cannot see why you put Image.FromStream(stream) and abaanaCCDataGridView... together?
Basically what you do is not incorrect. Get a MemoryStream from your byte[] and call Image.FromStream().
So I think these lines will work for you ...
byte[] mydata = (byte[])this.abaanaDataSet.abaanaCC.Rows[0]["CCImage"];
MemoryStream stream = new MemoryStream(mydata);
this.PpicBox.Image = Image.FromStream(stream);
... if the content of the byte[] is valid.

Convert raw images to bitmap in c#

My code currently looks like this:
if (fe == "CR2")
{
Image img = null;
byte[] ba = File.ReadAllBytes(open.FileName);
using (Image raw = Image.FromStream(new MemoryStream(ba)))
{
img = raw;
}
Bitmap bm = new Bitmap(img);
pictureBox1.Image = bm;
statusl.Text = fe;
}
When I open a RAW image the program stops and Visual Studio says:
Parameter is not valid: Image raw = Image.FromStream(new MemoryStream(ba))
Please help! How can I get a RAW file to show in a PictureBox ?
Create the bitmap like this:
Bitmap bmp = (Bitmap) Image.FromFile(open.FileName);
or without using bitmap:
this.pictureBox1.Image = Image.FromFile(open.FileName);
Example WPF:
BitmapDecoder bmpDec = BitmapDecoder.Create(new Uri(origFile),
BitmapCreateOptions.DelayCreation, BitmapCacheOption.None);
BitmapEncoder bmpEnc = new BmpBitmapEncoder();
bmpEnc.Frames.Add(bmpDec.Frames[0]);
Stream ms = new MemoryStream();
bmpEnc.Save(ms);
Image srcImage = Bitmap.FromStream(ms);
You're actually disposing an Image by specifying using (Image raw = Image.FromStream(new MemoryStream(ba))) later assigning the Disposed instance of image to picturebox which leads to this exception. To make to work you've to either don't dispose or clone the image.
Bitmap raw = Image.FromStream(new MemoryStream(ba) as Bitmap;
pictureBox1.Image = raw;
Or simply Clone
using (Image raw = Image.FromStream(new MemoryStream(ba)))
{
img = raw.Clone() as Bitmap;
}
Both of the above should work
you try this code :
private static void SaveImageToRawFile(string strDeviceName, Byte[] Image, int nImageSize)
{
string strFileName = strDeviceName;
strFileName += ".raw";
FileStream vFileStream = new FileStream(strFileName, FileMode.Create);
BinaryWriter vBinaryWriter = new BinaryWriter(vFileStream);
for (int vIndex = 0; vIndex < nImageSize; vIndex++)
{
vBinaryWriter.Write((byte)Image[vIndex]);
}
vBinaryWriter.Close();
vFileStream.Close();
}
private static void LoadRawFile(string strDeviceName, out Byte[] Buffer)
{
FileStream vFileStream = new FileStream(strDeviceName, FileMode.Open);
BinaryReader vBinaryReader = new BinaryReader(vFileStream);
Buffer = new Byte[vFileStream.Length];
Buffer = vBinaryReader.ReadBytes(Convert.ToInt32(vFileStream.Length));
vBinaryReader.Close();
vFileStream.Close();
}

Converting image to base64

I have the following code to convert image to base64:
private void btnSave_Click(object sender, RoutedEventArgs e)
{
StreamResourceInfo sri = null;
Uri uri = new Uri("Checked.png", UriKind.Relative);
sri = Application.GetResourceStream(uri);
BitmapImage bitmap = new BitmapImage();
bitmap.SetSource(sri.Stream);
WriteableBitmap wb = new WriteableBitmap(bitmap);
MemoryStream ms = new MemoryStream();
wb.SaveJpeg(ms, bitmap.PixelWidth, bitmap.PixelHeight, 0, 100);
byte[] imageBytes = ms.ToArray();
base64 = System.Convert.ToBase64String(imageBytes);
}
And the following code to get Bitmap image form base 64:
public static BitmapImage base64image(string base64string)
{
byte[] fileBytes = Convert.FromBase64String(base64string);
using (MemoryStream ms = new MemoryStream(fileBytes, 0, fileBytes.Length))
{
ms.Write(fileBytes, 0, fileBytes.Length);
BitmapImage bitmapImage = new BitmapImage();
bitmapImage.SetSource(ms);
return bitmapImage;
}
}
So when i convert and deconvert it is blank.
I know that deconverter works, because, when i give him exact string:
string base64="iVBORw0KGgoAAAANSUhEUgAAACQAAAAkCAQAAABLCVATAAACH0lEQVR42q3WoZKrMBQGYGRkIpHEoY9DMrh1nUGtzxPcGV7gCsTaK3iBCqa2ipmrVqLrWrmytjL3nBwoEGD30ja/6JaSj/wp3SEIXjpUoB+Oeg0zpoR+NsyoDVOgi39cbYHAy4MQTc0wOYZepxRBUkn9UxxEiNnXxyYwd6w/438hSddHJilv1tqv664Shle1DeJaJihPV9uNQ+NWBRK2QVSr+GjtaFzOIpdjKFShnoY+Gv0N0u0OVLexY48NQ+68JchdpQu/o1piVMu6faJdwjNWIAYyl55bqGUtbndO53TzCIpUpCkdlEm+V3J3Ir8r3uops2+FkTmvx832IGJwN97xS/5Ti0LQ/WLwtbxMal2ueAwvc2c8CAgSJip5U4+tKHECMlUzq2UcA9EyROuJi6/71dtzWAfVcq0Jw1CsYh13kDDteVoirE+zWtLVinQ8ZAS5YlVlvRHWfi3pakUQL0OOwmp/W/vN6Gt5zBIkzEezxnCtMJsxDIECTYmhp3bej4HHzaalNMyAnzE0UBKp6Z1Do2pwd3JkAH6CxlTs/bZOZ661yMwhohDLQqREMWz8UAvWoUQleggehG5dSPUbv28GJlnKHGJsqPi7vuG/MGTyCGslOtkCOayrGOa/indajdudb6FUpXoepgiLHIIMriddyzrkMBhGAqlOH4U2hKCT2j0NdU8jFbzpZ3LQlh9srPqEQ1Y9lEP2CVa99KHvH8mnrGGdl9V9AAAAAElFTkSuQmCC";
Which is my Checked.png converted in online converter. It decompreses perfectly.
And this is my base64, which i get by converting:
"/9j/4AAQSkZJRgABAQEAYABgAAD/2wBDAAEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQH/2wBDAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQH/wAARCAAkACQDASIAAhEBAxEB/8QAHwAAAQUBAQEBAQEAAAAAAAAAAAECAwQ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ms/GWpeIfEthc+JPCXhj/AIQTw9o+tyafrms6PpYB/Fiy7Tjn8aKluV2yY/2RRQB7r8CtS+E3h34wfCvxD8efBvib4hfBXRfHnhLVfir4E8G+ILfwv4o8YeALLWLO58UeHtD1+5t7mLTNQ1TSUurSKY/ZJZPN8i31XRLiWLWLL/W48Q/Bf/gmX/wXm/4Jg6V8PfgkPhtqfwYT4ey+EfgFrOleDorLxX+xt8SNA8Jnwz4Ot4fh9pmseE9d8E6x8M2t9Jt9T+HEOveHvD/jvwbY2+l2uq6n4D8Q6Vrd3/kEQxfuYiMcxp3PdB+Fff8A/wAE7v8AgpB+1H/wTJ+Omn/Gv9mzxpLp9veT6ba/Ez4Wa1NdXXwy+L/hayunmPhzxx4eS4ijnmhjuL1dC8UaebXxX4Unvry58P6tZi+1GG7AP9Q3/gpJ+2p+zz/wQi/4JraUnww8MeHNE1Lwp4PsfgV+x58FbcKIvEPju20OSDR9R1i3iaG81Dw34RiSbx98U/Ed3PBe69Ik1nc6w3jPxro7ah/kLfEnx946+L/xB8b/ABV+JviXVvG3xF+I/ivXvG/jrxdrlws+r+JfFfibU7nV9c1nUZQsStdX+o3dxcyCKKG3jMnlW0ENvHFGv6ff8Fgf+CqPxQ/4K0ftQQfHDxdoEnw7+HHgrwxZeCfgx8HY/EDeI7H4f6AUhv8AxNfXeqrY6Tba34q8X+JjcalrmvpoumS3OmWnhnw+8Mtj4YsGH5ReT9PzNAHF6guy4K4wdi5HXrmip9YXbesP+mcfr6UUAdHb+NTFbwQ3Hhnw5qE0MUcT310fEUd1ciKNI0e4Fh4hsrRptqDzJY7WOSeQvNO0szvI0v8AwnEX/QneFf8Av74t/wDmroooAP8AhOIv+hO8K/8Af3xb/wDNXSjxzECD/wAIb4UODnBl8XYPsceLAcH2IPoRRRQByWp6g+p3kl21taWm8KqW1lE0UEUaDaiKZZJriUgcGa6uLi4fjzJnwMFFFAH/2Q=="
My problem is that string which i get as base64 from my code - is incorrect *What i did wrong?*
What about trying:
public static BitmapImage base64image(string base64string)
{
byte[] fileBytes = Convert.FromBase64String(base64string);
using (MemoryStream ms = new MemoryStream(fileBytes))
{
Image streamImage = Image.FromStream(ms);
context.Response.ContentType = "image/jpeg";
streamImage.Save(context.Response.OutputStream, ImageFormat.Jpeg);
return streamImage;
}
}
I agree with Alexei that your code for reading the image in does look a little strange. I've recently written some code for a similar task that I was doing which might point you in the right direction:
string fileContent = null;
/* Check the file actually has some content to display to the user */
if (uploadFile != null && uploadFile.ContentLength > 0)
{
byte[] fileBytes = new byte[uploadFile.ContentLength];
int byteCount = uploadFile.InputStream.Read(fileBytes, 0, (int)uploadFile.ContentLength);
if (byteCount > 0)
{
fileContent = CreateBase64Image(fileBytes);
}
}
private string CreateBase64Image(byte[] fileBytes)
{
Image streamImage;
/* Ensure we've streamed the document out correctly before we commit to the conversion */
using (MemoryStream ms = new MemoryStream(fileBytes))
{
/* Create a new image, saved as a scaled version of the original */
streamImage = ScaleImage(Image.FromStream(ms));
}
using (MemoryStream ms = new MemoryStream())
{
/* Convert this image back to a base64 string */
streamImage.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
return Convert.ToBase64String(ms.ToArray());
}
}
not an answer: more of a long comment ... OP states that decoding code works perfectly fine, also it looks suspicios. Also code assumed to be verified to work on PNG images, but saving code explicitly produces valid JPG with SaveJpeg call...
Your code that creates stream for reading looks strange - you create stream over existing byte array, than write the same bytes into that stream, and that pass that stream without seeking back to 0 to some method.
Potential fix (assuming BitampImage can accept JPG stream):
don't call Write at all as stream already have the bytes you want
set ms.Position = 0 after writing to the stream.
Note: I'm not sure if it is OK to dispose stream that is a source for BitmapImage, you may need to remove using too.

Cannot implicitly convert type 'void' to 'byte[]'

The image is meant to be added to an update sql statement to update the image id a user changes the picture. I am trying to call the displayPhoto method into the savebtn method and assign it to residentImage variable as the image placeholder.
PhotoDisplay Method:
private void DisplayPhoto(byte[] photo)
{
if (!(photo == null))
{
MemoryStream stream = new MemoryStream();
stream.Write(photo, 0, photo.Length);
stream.Position = 0;
System.Drawing.Image image = System.Drawing.Image.FromStream(stream);
BitmapImage bitmapImage = new BitmapImage();
bitmapImage.BeginInit();
MemoryStream memoryStream = new MemoryStream();
image.Save(memoryStream, System.Drawing.Imaging.ImageFormat.Bmp);
memoryStream.Seek(0, SeekOrigin.Begin);
bitmapImage.StreamSource = memoryStream;
bitmapImage.EndInit();
ResidentImage.Source = bitmapImage;
ResidentProfileImage.Source = bitmapImage;
}
else
{
ResidentImage.Source = new BitmapImage(new Uri("pack://application:,,,/Resources/ResidentImage.jpg"));
}
}
Save Button Method:
private void btnSave_Click(object sender, RoutedEventArgs e)
{
Resident hello = new Resident();
hello.Doctor = new Doctor();
hello.Room = new Room();
hello.addtionalInformation = txtAdditionalInformation.Text;
hello.FirstName = txtForename.Text;
hello.Surname = txtSurname.Text;
hello.Title = txtTitle.Text;
hello.ResidentID = GlobalVariables.SelectedResident.ResidentID;
hello.Doctor.DoctorID = GlobalVariables.SelectedResident.Doctor.DoctorID;
hello.Room.RoomID= GlobalVariables.SelectedResident.Room.RoomID;
hello.Room.Name = txtRoomNo.Text;
hello.Allergies = txtResidentAlergies.Text;
hello.Photo = DisplayPhoto(hello.Photo);
hello.DateOfBirth = DateTime.Parse(txtDOB.Text);
ResidentData.Update(hello);
}
You have defined your DisplayPhoto function to be a 'void' function, meaning that it returns nothing.
Then how do you expect to get something back in hello.Photo = DisplayPhoto(hello.Photo);?
If you want to read something back from DisplayPhoto, probably you need to write something like this
public byte[] DisplayPhoto(byte[] photo)
{
if (!(photo == null))
{
MemoryStream stream = new MemoryStream();
// .......
return stream.ToArray();
}
else
{
// Convert your existing ResidentImage.Source to a byte array and return it
}
}
You are trying to set hello.Photo to the return value of DisplayPhoto yet it's return type is void, e.g. it returns nothing at all. Problematic line is here:
hello.Photo = DisplayPhoto(hello.Photo);
You need to make DisplayPhoto return a byte[]. Crude example: -
private byte[] DisplayPhoto(byte[] photo)
{
if (!(photo == null))
{
MemoryStream stream = new MemoryStream();
stream.Write(photo, 0, photo.Length);
stream.Position = 0;
System.Drawing.Image image = System.Drawing.Image.FromStream(stream);
BitmapImage bitmapImage = new BitmapImage();
bitmapImage.BeginInit();
MemoryStream memoryStream = new MemoryStream();
image.Save(memoryStream, System.Drawing.Imaging.ImageFormat.Bmp);
memoryStream.Seek(0, SeekOrigin.Begin);
bitmapImage.StreamSource = memoryStream;
bitmapImage.EndInit();
ResidentImage.Source = bitmapImage;
ResidentProfileImage.Source = bitmapImage;
return stream.ToArray();
}
else
{
ResidentImage.Source = new BitmapImage(new Uri("pack://application:,,,/Resources/ResidentImage.jpg"));
}
return new byte[0];
}

Categories

Resources