I need to convert a byte[] to an Image, but I cannot make it work in C#. If I save the bytearray to a file like this:
using (System.IO.FileStream fs = System.IO.File.Create("test.jpg"))
{
fs.Write(bytearray, 0, (int)lenght);
fs.Close();
}
And test.jpg shows properly. But when I try to make Image from the bytearray like this:
MemoryStream ms = new MemoryStream(bytearray);
pictureBox1.Image = Image.FromStream(ms);
It shows only black box.
I guess one problem is since you are creating test.jpg, it doesn't have any data and so the bytearray is empty.
Do something like :-
byte[] fileData = null;
using (var fs = new FileStream("C:\\1\\roses.jpg", FileMode.Open, FileAccess.Read))
{
var totalLength = (int)fs.Length;
using (var binaryReader = new BinaryReader(fs))
{
fileData = new byte[totalLength];
fs.Read(fileData, 0, totalLength);
fs.Close();
}
MemoryStream ms = new MemoryStream(fileData);
pictureBox1.Image = Image.FromStream(ms);
}
Okay, all was my bad. The code is correct, but the reason why it was showing only black screen was, becuase the picture was so big and it was black in the corners. And the pictureBox was not resizing it or anything so it showed its top right corner only.
Related
I'm developing a Windows Forms application where one of the things i need to do is, extract the image from .img file. I'm being able to read the normal jpg and png files, but not .img file.
I could not find much information on internet regarding this. I did find some code on msdn and i tried to get it to work. Below is the code and exception that is being thrown.
FileInfo file = new FileInfo(FilePath.Text);
FileStream f1 = new FileStream(FilePath.Text, FileMode.Open,
FileAccess.Read, FileShare.Read);
byte[] BytesOfPic = new byte[Convert.ToInt32(file.Length)];
f1.Read(BytesOfPic, 0, Convert.ToInt32(file.Length));
MemoryStream mStream = new MemoryStream();
mStream.Write(BytesOfPic, 0, Convert.ToInt32(BytesOfPic.Length));
Bitmap bm = new Bitmap(mStream, false);
mStream.Dispose();
// ImageBox is name of a PictureBox
ImageBox.image = bm; // this line is throwing the error
Exception caught
System.ArgumentException: Parameter is not valid.
at System.Drawing.Bitmap..ctor(Stream stream, Boolean useIcm)
at A02_Stegnography.Form1.ReadImgFile() in C:\Users\tiwar\Desktop\A02-Stegnography\A02-Stegnography\Form1.cs:line 65
I'm sorry if this is a stupid question. I hope i have provided enough information but if i haven't please let me know.
FileInfo file = new FileInfo(FilePath.Text);
FileStream f1 = new FileStream(FilePath.Text, FileMode.Open,
FileAccess.Read, FileShare.Read);
byte[] BytesOfPic = new byte[Convert.ToInt32(file.Length)];
f1.Read(BytesOfPic, 0, Convert.ToInt32(file.Length));
using (MemoryStream mStream = new MemoryStream())
{
mStream.Write(BytesOfPic, 0, BytesOfPic.Length);
mStream.Seek(0, SeekOrigin.Begin);
Bitmap bm = new Bitmap(mStream);
// ImageBox is name of a PictureBox
ImageBox.image = bm;
}
You can try my solution for problem
Ive got a question I am having a case of rest response that is always string, it suppose to download content of the file, but there can be many different files, for example PNG, now if I'm getting a string in response is it possible to convert it back to PNG at the end, I tried something like:
byte[] array = Encoding.ASCII.GetBytes(result.data); //response content
MemoryStream ms = new MemoryStream(array);
Image i = Image.FromStream(ms);
I dont think im getting base64 string from rest looks like (part of it, and if i remmebr base64 ends with 3 === and don't have any non printable chars):
�PNG\r\n\n\0\0\0\rIHDR\0\0�\0\0\0�\b\0\0\0���\0\0\0sRGB\0���\0\0\0gAMA\0\0��\v�a\0\0\0\tpHYs\0\0t\0\0t�fx\0\0\f\aIDATx^��!x�L���Jde%�yY�D�H$�d%2��S��Hd%y�<�ӹ�B�ٝ�O�mﺔ��d����\r\0���\a�(H|\0���\a�(H|\0���\a�(H|\0���\a�(H|\0���\a�(H|\0���\a�(H|\0���\a�(H|\0���\a�(H|\0���\a�(H|\0���\a�(H|\0�\"D�WU��v������r��o#\f!��y�����K�\0�'D�O�SM�\f�����\0��Dǯ�z4�R��C�7\0��+�\0�\0Q��\0�\0Q��UU���ļO ?�������!�#J�>���|D��$>\f�|D��$>\f��7X,�?�_\v]�V�^/�=��#4$�����$:��P9
Assuming you are returning base 64 string from the API response, you can do something like this
byte[] bytes = Convert.FromBase64String(result.data);
Image image;
using (MemoryStream ms = new MemoryStream(bytes))
{
image = Image.FromStream(ms);
}
return image;
Or you can save it directly to the file
string filePath = "Image.png";
File.WriteAllBytes(filePath, Convert.FromBase64String(result.data));
EDIT 1:
How are you returning data from your web API? You could do something like this to return byte array and then use this array directly to write to stream.
var result = new HttpResponseMessage(HttpStatusCode.OK);
String filePath = HostingEnvironment.MapPath("~/imagename.png");
FileStream fileStream = new FileStream(filePath, FileMode.Open);
Image image = Image.FromStream(fileStream);
MemoryStream memoryStream = new MemoryStream();
image.Save(memoryStream, ImageFormat.Jpeg);
result.Content = new ByteArrayContent(memoryStream.ToArray());
result.Content.Headers.ContentType = new MediaTypeHeaderValue("image/png");
return result;
and on the client side you can do something like
var data = response.Content.ReadAsByteArrayAsync().Result;
Image image;
using (MemoryStream ms = new MemoryStream(data))
{
image = Image.FromStream(ms);
}
return image;
I am trying to convert bitmap Image to Byte array. I have select all the image by using MediaLibrary class and added it into a list of bitmap images. Here is my code
using (IsolatedStorageFile store = IsolatedStorageFile.GetUserStoreForApplication())
{
if (!store.DirectoryExists("ImagesZipFolder"))
{
store.CreateDirectory("ImagesZipFolder");
for (int i = 0; i < imgname.Count(); i++)
{
using (IsolatedStorageFileStream stream = new IsolatedStorageFileStream(#"ImagesZipFolder\" + imgname[i], System.IO.FileMode.CreateNew, store))
{
byte[] bytes = null;
using (MemoryStream ms = new MemoryStream())
{
WriteableBitmap wBitmap = new WriteableBitmap(ImgCollection[i]);
wBitmap.SaveJpeg(ms, wBitmap.PixelWidth, wBitmap.PixelHeight, 0, 100);
stream.Seek(0, SeekOrigin.Begin);
bytes = ms.GetBuffer();
stream.Write(bytes, 0, bytes.Length);
}
// byte[] bytes = Encoding.UTF8.GetBytes(imgname[i]);//new byte[ImgCollection[i].PixelWidth * ImgCollection[i].PixelHeight * 4];
// stream.Write(bytes, 0, bytes.Length);
}
}
}
else {
directory = true;
}
}
Basically what I am trying to do is, selecting all images or photo from device and create a zip file of that images. I was successful in creating a zip file of images. When I extract that file there is some images, but the problem is when I double click on image, I can't see that image. I think the problem is in reading the bytes of image. I am not getting what's wrong? Is my code is correct ?
Perhaps you can try the below. I know this code maintains the image, so if you have no luck using this, you may have a different issue.
// Convert the new image to a byte[]
ImageConverter converter = new ImageConverter();
byte[] newBA = (byte[])converter.ConvertTo(newImage, typeof(byte[]));
The ImageConverter is of the System.Drawing namespace.
Update:
http://msdn.microsoft.com/en-GB/library/system.windows.media.imagesourceconverter.convertto.aspx
You should be able to use this in place of the System.Drawing type I suggested.
There is no need to save the WriteableBitmap to a MemoryStream and then copy it to an IsolatedStorageFileStream. Just save the bitmap directly to the IsolatedStorageFileStream.
using (IsolatedStorageFileStream stream = new IsolatedStorageFileStream(#"ImagesZipFolder\" + imgname[i], System.IO.FileMode.CreateNew, store))
{
WriteableBitmap wBitmap = new WriteableBitmap(ImgCollection[i]);
wBitmap.SaveJpeg(stream, wBitmap.PixelWidth, wBitmap.PixelHeight, 0, 100);
}
This will allow you to save on memory as well. If you really want to save memory, you could reuse the WriteableBitmap.
I am using
File.Delete("new13.jpg");
FileStream stream1 = new FileStream("new13.jpg", FileMode.Create);
JpegBitmapEncoder encoder1 = new JpegBitmapEncoder();
encoder1.FlipHorizontal = true;
encoder1.FlipVertical = false;
encoder1.QualityLevel = 30;
//encoder.Rotation = Rotation.Rotate90;
encoder1.Frames.Add(BitmapFrame.Create(bitmap));
encoder1.Save(stream1);
when my camera takes a new picture it is stored as "new13.jpg" but when i again take picture it shows exception that this image it is being used by another process . I am doing some image processing on image after being taken. How do i get rid of this exception .
You should close the stream after saving to it:
encoder1.Save(stream1);
stream1.Close();
Or better use a using block like this:
using (FileStream stream = new FileStream("new13.jpg", FileMode.Create))
{
encoder1.Save(stream);
}
what is the easiest way to translate a Bitmap & Png to string AND BACK AGAIN. Ive been trying to do some saves through memory streams and such but i cant seem to get it to work!
Appearently i wasnt clear,
what i want, is to be able to translate a Bitmap class, with an image in it.. into a system string. from there i want to be able to throw my string around for a bit, and then translate it back into a Bitmap to be displayed in a PictureBox.
Based on #peters answer I've ended up using this:
string bitmapString = null;
using (MemoryStream memoryStream = new MemoryStream())
{
image.Save(memoryStream, ImageFormat.Png);
byte[] bitmapBytes = memoryStream.GetBuffer();
bitmapString = Convert.ToBase64String(bitmapBytes, Base64FormattingOptions.InsertLineBreaks);
}
and
Image img = null;
byte[] bitmapBytes = Convert.FromBase64String(pictureSourceString);
using (MemoryStream memoryStream = new MemoryStream(bitmapBytes))
{
img = Image.FromStream(memoryStream);
}
From bitmap to string:
MemoryStream memoryStream = new MemoryStream();
bitmap.Save (memoryStream, ImageFormat.Png);
byte[] bitmapBytes = memoryStream.GetBuffer();
string bitmapString = Convert.ToBase64String(bitmapBytes, Base64FormattingOptions.InsertLineBreaks);
From string to image:
byte[] bitmapBytes = Convert.FromBase64String(bitmapString);
MemoryStream memoryStream = new MemoryStream(bitmapBytes);
Image image = Image.FromStream(memoryStream);