So I am trying to convert an array of bytes to an image but I get this error:
System.ArgumentException: 'Parameter is not valid.' The byte[] comes from a database in SQL server where the data type is "image".
I have already tried every solution that I have found offered in other questions in StackOverflow and they have not worked for me; Here is my code:
//biblioteca.herramientas is where I make the connection with the server
DataSet dataset_Image;
dataset_Image = Biblioteca.Herramientas(string.Format("SELECT * FROM Image WHERE id_Image = " + 1));
array = (byte[])dataset_Image.Tables[0].Rows[0]["image"];
public byte[] TheImage
{
set
{
theImage = ImageConversor.ByteArrayToImage(value);
PictureBox2.Image = theImage;
}
}
This is where I have the error:
public class ImageConversor
{
public static Image ByteArrayToImage(byte[] byteArrayIn)
{ //HERE THE ERROR APPEARS
MemoryStream ms = new MemoryStream(byteArrayIn);
Image returnImage = Image.FromStream(ms);
return returnImage;
}
}
The following picture is the SQL table that I am accessing to:
And that is all, if you need more info I will share it, thank you for your time, hope you have a good day. (:
EDIT:
The code works fine if I add the picture directly from SQLS, changing the column "image"(where the picture is stored) datatype from "image" to "varbinary(MAX)" and then using the following code to insert the image:
insert into Image select * from openrowset (bulk N'picture directory', single_blob) as image
The problem is that I can not use that to add the picture, but I dont know, maybe it helps to solve this problem :/
Related
So I collect a varbinary(MAX) value from a database where an image is stored.
It gets converted to byte[], then the aim is to display this in an image control.
This is where I read from the database
public TemplateData(SqlDataReader dr)
{
initialiseData();
if (dr.HasRows)
{
Logo = (byte[])dr["Logo"];
//Logo = dr["Logo"].ToString();
TemplateId = dr["TemplateId"].ToString();
Comment = dr["Comment"].ToString();
SchemeCode = dr["SchemeCode"].ToString();
Version = dr["Version"].ToString();
}
}
This is where the values are displayed into the corresponding controls
protected void ddSchemeCode_SelectedIndexChanged(object sender, EventArgs e)
{
if (ddSchemeCode.SelectedIndex > 0)
{
// Existing Data to load from database
TemplateData temp = DataClass.ReturnData(ddSchemeCode.SelectedItem.Text);
if (temp != null)
{
txtVersion.Text = temp.Version;
txtComment.Text = temp.Comment;
txtSchemeCode.Text = temp.SchemeCode;
txtTemplateId.Text = temp.TemplateId;
img.Src = temp.Logo;
}
So at the moment I am passing a byte[] into the source of an image control, where it would instead like a string. I've tried converting it to a string with Convert.ToBase64String(Logo) and ToString(Logo) but these do not work.
Any help is greatly appreciated. Cheers guys and gals.
Try converting the byte array to image and assign it to picturebox as below,
try
{
using (MemoryStream mStream = new MemoryStream())
{
// where pData is your byte array
mStream.Write(pData, 0, Convert.ToInt32(pData.Length));
Image originalImage = Image.FromStream(mStream);
picBox.Image = originalImage;
}
}
catch (Exception ex)
{
}
Hope it helps.
As you may have noticed, you cannot "print" an image in a webpage. You need to get a little bit creative now.
What you want to look into is Response.BinaryWrite. More information about that, here: https://msdn.microsoft.com/en-us/library/system.web.httpresponse.binarywrite%28v=vs.110%29.aspx
You will probably also need a generic ashx handler. Here is an example of how to show a picture using a handler: http://www.dotnetperls.com/ashx
My suggestion would be to store the logo as a byte[] into the http session. Put the source of the image to theHttpHandlerYourGonnaCreate.ashx. You can then binary write the byte[] you've stored into the session there.
Hope this helps!
As Michael shows here, you can convert the byte array to a Bitmap object with something like this:
Bitmap bitmap = null;
using (MemoryStream imageStream = new MemoryStream(imageData))
{
bitmap = new Bitmap(imageStream);
}
It isn't entirely clear what you're using for a control to show the image, but any control that can display an image should be able to take a Bitmap or Image object.
I have an image stored in my database (sql) as a varbinary variable and I want to save it as a jpg file in a directory with c#. how should I do that? I have a method which return a variable of type image and now the question is how to save it?
I suppose that you got byte array and you just need to convert it to an image file:
public static void ByteArrayToImage(byte[] imgByte)
{
MemoryStream ms = new MemoryStream(imgByte);
Image img = Image.FromStream(ms);
img.Save(#"C:\imageTest.png");
}
Simple, use Image.Save.
Image img = YourMethodWhichReturnsImage();
string loationTosave = #"C:\fileToSave.jpg";
img.Save(loationTosave);
I Tried many solutions to remove Generic error Occured in GDI + but nothing is working for me , I am posting Codes that i had used.This error occured in server machine
Images bytes are stored successfully in Database but doesnt retrieve on PictureBox.
1st Method :
ODetail.InsuranceCardImages Contains Bytes of Images From Database.
pcinsurance is my PictureBox
System.Byte[] imagefront = (byte[])oDetail.InsuranceCardImage;
//this.pcInsurance.Image = Utility.byteArrayToImage(oDetail.InsuranceCardImage);
MemoryStream ms = new MemoryStream(imagefront);
try
{
//Process currentProcess1 = Process.GetCurrentProcess();
Image returnImage = Image.FromStream(ms);
pcInsurance.Image= returnImage;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
try
{
ms.Flush();
ms.SetLength(0);
ms.Close();
ms.Dispose();
ms = null;
//GC.Collect();
}
catch
{
}
}
2nd Method :
where pcinsurance is my PictureBox
byte[] byteArray = oDetail.InsuranceCardImage;
var imageStream = new MemoryStream(byteArray);
var image = (Bitmap)Bitmap.FromStream(imageStream);
pcInsurance.Image = image;
Still cant fix this issue ,
Kindly provide your solutions so that i will carry on my work
Thank You.
Why do you use ms.Close();,ms.Dispose(); and ms = null;?
You dispose this stream twice and afterwards set it to null.
Finally is performed always so MemoryStream is always disposed.
I suspect that all resources are released before they're used by GDI. I experienced similar problem some time ago.
According to MSDN:
http://msdn.microsoft.com/en-us/library/93z9ee4x.aspx
You must keep the stream open for the lifetime of the Image.
The solution was a creation a Bitmap object:
Bitmap bmp = new Bitmap(ms);
this.pcInsurance.Image = bmp;
In fact I used using statement to simplify code, closing stream before final braces. Works exactly the same but is shorter and in my opinion more readable.
Bitmap and picturebox.Imageobjects must be disposed before setting another picture.
Hope this helps.
I'm trying to make use of an image pasted from the clipboard, like a screenshot.
Here is a snippet of code:
public void PasteImage(Image pasteImage)
{
MemoryStream image = new MemoryStream();
pasteImage.Save(image, pasteImage.RawFormat);
image.Position=0;
byte[] byteImage = image.ToArray();
On the line:
pasteImage.Save(image, pasteImage.RawFormat);
I get this error:
An unhandled exception of type 'System.ArgumentNullException' occurred
in System.Drawing.dll
Additional information: Value cannot be null.
I'm following previous stackoverflow posts I've found on this topic, such as How to compare two images using byte arrays, and How to convert image in byte array, and just can't get it to work.
I'm wondering if there is something specific about images retrieved from the clipboard. I'm using this code to fetch the image:
if (Clipboard.ContainsImage())
{
Image pasteImage = GetClipboardImage();
PasteImage(pasteImage);
}
EDIT
This is the code behind GetClipboardImage():
public Image GetClipboardImage()
{
System.Drawing.Image returnImage = null;
if (Clipboard.ContainsImage())
{
returnImage = Clipboard.GetImage();
}
return returnImage;
}
If I put a breakpoint on the line that errors I can see that both pasteImage and pastImage.RawFormat are not null:
This looks relevant as an example Ill have a crack at that and report back: How can I get an image out of the clipboard without losing the alpha channel in .NET?
Looking at the MSDN article for Save Image, you might want to try:
Instead of
pasteImage.Save(image, pasteImage.RawFormat);
try
pasteImage.Save(image, System.Drawing.Imaging.ImageFormat.RawFormat)
I am trying to convert a varbinary to an image in my silverlight project.
First I get the Binary from my database in my service.
[OperationContract]
public byte[] getAfbeelding(int id)
{
var query = (from p in dc.Afbeeldings
where p.id == id
select p.source).Single();
byte[] source = query.ToArray();
Then I try to convert the varbinary to an image, using code found on StackOverflow:
public static string convertToImage(byte[] source)
{
MemoryStream ms = new MemoryStream(source);
Image img = Image.FromStream(ms);
return img.Source.ToString();
}
But as it turns out, the silverlight Image does not have a .FromStream, I tried all the examples found in this thread but NONE of them work in silverlight.
'System.Windows.Controls.Image' does not contain a definition for 'FromStream'
So yeah, I'm kinda lost and am not sure what to do.
Any ideas on how to do this in silverlight?
You're almost right. The following code should be all you need:
var bitmapImage = new BitmapImage();
bitmapImage.SetSource(new MemoryStream(imageData));
newImage.Source = bitmapImage;
where imageData is of type byte[] and newImage is the image you want to update.
you sould have a look at WriteableBitmap.
there is a pretty nice set of extensions freely available on codepelex or Nuget