I have a data table called dtchild and it contains a column named FILE_CONTENT. In my data table, FILE_CONTENT data is stored as a byte[] array.
How to retrieve FILE_CONTENT data from the data table and convert it into an image?
// bytes is the byte[] array of your file content :
using(MemoryStream ms = new MemoryStream(bytes))
{
var Image = Image.FromStream(ms);
}
Considering you want to show image in asp.net web forms
Try this code , on aspx page :
<img id='yourID' runat='server'/>
On CS page
byte[] Binary = (byte[])(dt.Rows[0]["Your column"]);
string base64string= Convert.ToBase64String(Binary, 0, Binary.Length);
yourID.Src = "data:image/jpg;base64," + base64String;
byte[] imgData = (byte[])dt.Rows[0]["Photo"];
MemoryStream ms = new MemoryStream(imgData);
Image img = Image.FromStream(ms);
pictureBox1.Image = img;
Related
I retrieve an image as a byte arrary stored in a database convert it to a bitmap and display it in an Imageview. I want to be able to retrieve that image from the Imageview and store it back to the database. My database retrieval code is:
TheService myService = new TheService.DataInterface();
DataSet MyPhoto = myService.GetPhoto(id);
byte[] imageBytes = (byte[])MyPhoto.Tables[0].Rows[0][0];
Bitmap bitmap = BitmapFactory.DecodeByteArray(imageBytes, 0, imageBytes.Length);
imageview.SetImageBitmap(bitmap);
At some point the image is changed and I need to store it back in the database. How would I get the image out of the imageview? Everything I've seen thus far deals with an attached drawable, there is no drawable in this case.
There doesn't seem to be a method like:
Bitmap photo = imageview.GetCurrentImage();
Any assistance would be appreciated.
**** UPDATED ****
Once I get the image I need to convert it into a byte array to save it into the database. I've tried several different methods with no success, the latest is:
using Java.Nio;
public static byte[] ImageToByte(Bitmap bitmap)
{
var bytes = new Byte[30000];
try
{
var byteBuffer = ByteBuffer.Allocate(bitmap.ByteCount);
bitmap.CopyPixelsToBuffer(byteBuffer);
bytes = byteBuffer.ToArray<byte>();
return bytes;
}
catch (Exception ex)
{
var message = ex.Message;
return bytes;
}
}
This generates an exception "Unable to cast from 'java/nio/HeapByteBuffer' to '[B'"
What you need to do is something like below:
BitmapDrawable bitmapDrawable = ((BitmapDrawable) imageView.Drawable);
Bitmap bitmap;
if(bitmapDrawable==null){
imageView.BuildDrawingCache();
bitmap = imageView.GetDrawingCache();
imageView.BuildDrawingCache(false);
}else
{
bitmap = bitmapDrawable .Bitmap;
}
Where imageView is the imageView control from which you want your bitmap
Update:
Convert from bitmap to byteArray something like this:
byte[] bitmapData;
using (var stream = new MemoryStream())
{
bitmap.Compress(Bitmap.CompressFormat.Png, 0, stream);
bitmapData = stream.ToArray();
}
I am Trying to Convert a Base64 encoded string to A Png Image, But the Code Shows Exception of Parameter is Not Valid on Image.FromStream(). After Debugging i cam up with this error on MemoryStream Object "ReadTimeout = 'ms.ReadTimeout' threw an exception of type 'System.InvalidOperationException'" . I am stuck, Is there any Solution or Alternative to Convert String to Png in C#?
Here is My code
string code = "string";
var databytes = Encoding.Unicode.GetBytes(code);
var base64 = Convert.ToBase64String(databytes);
Byte[] Bytes = Convert.FromBase64String(base64);
//Stream bytes
MemoryStream ms = new MemoryStream(Bytes, 0, Bytes.Length);
//convert image
Image newImage = Image.FromStream(ms);
newImage.Save("~/Content/");
Try this:
byte[] bytes = Convert.FromBase64String(base64);
Image image;
using (MemoryStream ms = new MemoryStream(bytes))
{
image = Image.FromStream(ms);
}
You can convert Base64 string into png in this way:
byte[] bytes = Convert.FromBase64String(base64);
Image image;
using (MemoryStream ms = new MemoryStream(bytes))
{
image = Image.FromStream(ms);
image.Save("~/Content/", System.Drawing.Imaging.ImageFormat.Png);
}
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'm trying to load a pre-saved images from an SQL Server CE VarBinary column into a PictureBox.
The column content is a bitmap image stored in varbinary format.
MemoryStream ms = new MemoryStream();
byte[] outbyte = new byte[100];
Int32 ordinal = 0;
conn.Open();
SqlCeDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
ordinal = reader.GetOrdinal("FaceStamp");//FaceStamp: VarBinary column storing Bmp.
outbyte = (byte[])reader[ordinal];
ms.Write(outbyte, 0, outbyte.Length);
ms.Seek(0, SeekOrigin.Begin);
pictureBox1.Image = Image.FromStream(ms);
}
conn.Close();
// Code below is the code I used to save the Bitmap image to the database
Bitmap bmi = cam.GetBitmap(); // Capture image from webcam which I've tested working.
ImageConverter converter = new ImageConverter();
byte[] byteArray = new byte[0];
byteArray = (byte[])converter.ConvertTo(bmi, typeof(byte[]));
insert.Parameters.AddWithValue("#image", byteArray);
insert.ExecuteNonQuery();
I get an error at the following line:
pictureBox1.Image = Image.FromStream(ms);
Saying
{"Parameter is not valid."}
Any tips?
Thank you.
I usually do the following when converting images saved as byte arrays:
byte[] outbyte = (byte[])reader[ordinal];
using (MemoryStream ms = new MemoryStream(outbyte))
{
Bitmap image = new Bitmap(ms);
pictureBox1.Image = image;
}
For converting the original image to a byte array you can take a look at this SO question.
I'm trying to convert a byte array to a bitmap but it always shows me:
System.ArgumentException: Parameter is not valid.
My code is as follows:
I'm passing the bytes through a webservice with:
string DecodedString = string.Empty;
DecodedString = System.Text.Encoding.GetEncoding(1251).GetString(bytes);
sResult = sResult + "<Photo>" +XmlConvert.EncodeName(DecodedString) + "</Photo>";
and in my webPage:
byte[] bytes = (Byte[])System.Text.Encoding.GetEncoding(1251).GetBytes(XmlConvert.DecodeName(xDocument.SelectSingleNode("Response/Images/Photo").InnerText));
System.IO.MemoryStream ms = new System.IO.MemoryStream(bytes);
System.Drawing.Bitmap b = new System.Drawing.Bitmap(ms);//(System.Drawing.Image.FromStream(ms));
Try passing the string as a Base64:
string DecodedString = string.Empty;
DecodedString = System.Convert.ToBase64String(bytes)
sResult = sResult + "<Photo>" +XmlConvert.EncodeName(DecodedString) + "</Photo>";
...
byte[] bytes = System.Convert.FromBase64String(xDocument.SelectSingleNode("Response/Images/Photo").InnerText);
System.IO.MemoryStream ms = new System.IO.MemoryStream(bytes);
System.Drawing.Bitmap b = System.Drawing.Image.FromStream(ms);
You also won't need to use XmlConvert to encode/decode the string.
I did it, with the help of all of you, here is my page code
byte[] bytes = System.Convert.FromBase64String(xDocument.SelectSingleNode("Response/Images/Photo").InnerText);
System.IO.MemoryStream ms = new System.IO.MemoryStream(bytes);
System.Drawing.Bitmap b = new System.Drawing.Bitmap(ms); //(Bitmap)System.Drawing.Image.FromStream(ms);
System.Drawing.Imaging.FrameDimension frameDim;
frameDim = new System.Drawing.Imaging.FrameDimension(b.FrameDimensionsList[0]);
int NumberOfFrames = b.GetFrameCount(frameDim);
string[] paths = new string[NumberOfFrames];
for (int i = 0; i < NumberOfFrames; i++)
{
b.SelectActiveFrame(frameDim, i);
System.Drawing.Bitmap bmp = new System.Drawing.Bitmap(b);
paths[i] = imagePathfile.Remove(imagePathfile.Length - 4, 4) + i.ToString() + ".gif";
bmp.Save(paths[i], System.Drawing.Imaging.ImageFormat.Gif);
//bmp.Save(Response.OutputStream, System.Drawing.Imaging.ImageFormat.Gif);
bmp.Dispose();
}
Image1.Src = paths[0];
//Check if there's more than 1 image cause its a TIFF
if (paths.Length>1)
{
Image2.Src = paths[1];
}
I had a similar problem recently, but using Silverlight. I ended up needing to create a Custom HTTP Handler in order to pass the byte[] that defined the image back as a stream.
See http://www.dotnetcurry.com/ShowArticle.aspx?ID=220
Edit: This allows you to avoid worrying about XML encoding, and passes the image back in Binary form... YMMV
According to MSDN:
ArgumentException - The stream does not have a valid image format
I believe your problem is in the original byte[] array you are passing to the web service.
According to one of your comments, you did:
System.IO.FileStream fs = new System.IO.FileStream(sPath, System.IO.FileMode.Open, System.IO.FileAccess.Read);
int streamLength = Convert.ToInt32(fs.Length);
bytes = new byte[streamLength];
fs.Read(bytes, 0, streamLength);
fs.Read returns the number of bytes that have been read into the byte array; it doesn't always read the entire file!
Try using the StreamFile method from http://www.dotnetspider.com/resources/4515-convert-file-into-byte-array.aspx. (First result of Google search)
Try this:
byte[] bytes = System.Convert.FromBase64String(xDocument.SelectSingleNode("Response/Images/Photo").InnerText);
System.Drawing.ImageConverter imageConverter = new System.Drawing.ImageConverter();
Image image = imageConverter.ConvertFrom(bytes) as Image;
System.Drawing.Bitmap b = new System.Drawing.BitMap(image);
EDIT
Take a look at this:
Transfer any files on Web services by c#
actually i had been meet this problem, In my case, when i use IE browser, it is ok but when use another browser it always have the same error.
"Parameter is not valid exception is always happening in the same line of code:
System.Drawing.Image.FromStream(ms));"
So i think it seems this issue depend on browser and type of image (JPEG,JPEG2000).
Here is some code I used converting bytes to an image for a unit test:
protected override Image LoadImage()
{
//get a temp image from bytes, instead of loading from disk
//data:image/gif;base64,
byte[] bytes = Convert.FromBase64String("R0lGODlhAQABAIAAAAAAAAAAACH5BAAAAAAALAAAAAABAAEAAAICTAEAOw==");
Image image;
using (MemoryStream ms = new MemoryStream(bytes))
{
image = Image.FromStream(ms);
}
return image;
}
To my understanding, the image can not be shown because the format of the image's bytes is not correct. Every image format has its own head or something.