How to convert PictureBoxImage to byte array - c#

How can I convert a PictureBox.Image to byte array to store in database directly ..
I tried the following code but they all give me the same error " a generic error occurred in GDI + "
public static byte[] ImageToByte(Image img)
{
ImageConverter converter = new ImageConverter();
return (byte[])converter.ConvertTo(img, typeof(byte[]));
}
public byte[] convertImageToByteArray(System.Drawing.Image image)
{
using (MemoryStream ms = new MemoryStream())
{
image.Save(ms, System.Drawing.Imaging.ImageFormat.Gif);
// or whatever output format you like
return ms.ToArray();
}
}
P.S I am running the program as Administrator too

Related

When i try to convert base64string to Image in c#

When i try to convert a base64string to an Image in C#, I'm getting output as "System.Drawing.Bitmap" instead of the actual Image:
public Image DownFile(string base64String)//string file
{
//Convert Base64 String to byte[]
byte[] imageBytes = Convert.FromBase64String(base64String);
MemoryStream ms = new MemoryStream(imageBytes, 0, imageBytes.Length);
//Convert byte[] to Image
ms.Write(imageBytes, 0, imageBytes.Length);
Image image = Image.FromStream(ms, true);
image.Save("E:/Project Utilitie Connection/FileDownloadTask/Images", System.Drawing.Imaging.ImageFormat.Jpeg);
return image;
}
try a using statement for the MemoryStream, like so:
byte[] bytes = Convert.FromBase64String(base64String);
Image image;
using (MemoryStream ms = new MemoryStream(bytes))
{
image = Image.FromStream(ms);
}
return image;
The framework is converting the Image object to string which is why you are seeing System.Drawig.Bitmap
Create a response, giving it the bytes from the converted base64 string and then setting the content type for response so the client will know how to render the content.
public class ValuesController : ApiController {
[HttpGet]
public IHttpActionResult DownFile(string base64String) {
if (!string.IsNullOrWhiteSpace(base64String)) {
byte[] imageBytes = Convert.FromBase64String(base64String);
var response = Request.CreateResponse(HttpStatusCode.OK);
response.Content = new ByteArrayContent(imageBytes);
response.Content.Headers.ContentType = new MediaTypeHeaderValue("image/jpg");
return ResponseMessage(response);
}
return BadRequest();
}
}
This is a very simplified example to demonstrate how it can be done. Take some time to review and understand what was done so that it can be implemented into your particular scenario.

Unable to convert Images stored in resource file to Base64 string in Asp.net [C#]

I am trying to get images stored in resource file and then trying to convert it to base64 string. however it generate garbage string below is my code:
String imgBase64=Base64FromByteArray(ExtractResource(Properties.Resources.products_tipp_110));
public static byte[] ExtractResource(Bitmap image)
{
MemoryStream ms = new MemoryStream();
image.Save(ms, ImageFormat.Png);
if (ms == null)
return null;
byte[] imageByteArray = new byte[ms.Length];
ms.Read(imageByteArray, 0, imageByteArray.Length);
return imageByteArray;
}
private static string Base64FromByteArray(byte[] image)
{
return "base64:" + Convert.ToBase64String(image);
}
output:
base64:AAAAAAAAAAAAAAAAAAAAAAAAAAAAA..... with all A's
Can you try this byte[] imageByteArray = ms.ToArray() to convert the memory stream into byte array as below.
Also, make sure your image is png as you have used ImageFormat.Png
String imgBase64=Base64FromByteArray(ExtractResource(Properties.Resources.products_tipp_110));
public static byte[] ExtractResource(Bitmap image)
{
MemoryStream ms = new MemoryStream();
image.Save(ms, ImageFormat.Png);
if (ms == null)
return null;
byte[] imageByteArray = ms.ToArray();;
return imageByteArray;
}
private static string Base64FromByteArray(byte[] image)
{
return "base64:" + Convert.ToBase64String(image);
}
Give this function Image and the format of Image, it will return you string.
public string ImageToBase64(Image image,
System.Drawing.Imaging.ImageFormat format)
{
using (MemoryStream ms = new MemoryStream())
{
// Convert Image to byte[]
image.Save(ms, format);
byte[] imageBytes = ms.ToArray();
// Convert byte[] to Base64 String
string base64String = Convert.ToBase64String(imageBytes);
return base64String;
}
}

C# storing Byte[] and retrieving it from MySQL

I'm inserting the byte[] file into MySQL BLOB column, but I can not show the image when retrieving. I have one function to store the image as byte[]
public byte[] imageToByteArray(Image imageIn)
{
MemoryStream ms = new MemoryStream();
imageIn.Save(ms, Imaging.ImageFormat.Jpeg);
return ms.ToArray();
}
Which I call this way:
Image img = Image.FromFile('trend.jpg');
#field = imageToByteArray(img);
In PhpMyAdmin it shows this way
On the other hand, when I try to retrieve the image into a picturebox, I receive an error.
byte[] bytes = (byte[])item["image"];
pictureBox1.Image = byteArrayToImage(bytes);
public Image byteArrayToImage(byte[] byteArrayIn)
{
MemoryStream ms = new MemoryStream(byteArrayIn);
Image returnImage = Image.FromStream(ms);
return returnImage;
}
Invalid character in a base-64

C# Base64 String to JPEG Image

I am trying to convert a Base64String to an image which needs to be saved locally.
At the moment, my code is able to save the image but when I open the saved image, it says "Invalid Image".
Code:
try
{
using (var imageFile = new StreamWriter(filePath))
{
imageFile.Write(resizeImage.Content);
imageFile.Close();
}
}
The Content is a string object which contains the Base64 String.
First, convert the base 64 string to an Image, then use the Image.Save method.
To convert from base 64 string to Image:
public Image Base64ToImage(string base64String)
{
// Convert base 64 string to byte[]
byte[] imageBytes = Convert.FromBase64String(base64String);
// Convert byte[] to Image
using (var ms = new MemoryStream(imageBytes, 0, imageBytes.Length))
{
Image image = Image.FromStream(ms, true);
return image;
}
}
To convert from Image to base 64 string:
public string ImageToBase64(Image image,System.Drawing.Imaging.ImageFormat format)
{
using (MemoryStream ms = new MemoryStream())
{
// Convert Image to byte[]
image.Save(ms, format);
byte[] imageBytes = ms.ToArray();
// Convert byte[] to base 64 string
string base64String = Convert.ToBase64String(imageBytes);
return base64String;
}
}
Finally, you can easily to call Image.Save(filePath); to save the image.
So with the code you have provided.
var bytes = Convert.FromBase64String(resizeImage.Content);
using (var imageFile = new FileStream(filePath, FileMode.Create))
{
imageFile.Write(bytes ,0, bytes.Length);
imageFile.Flush();
}
public Image Base64ToImage(string base64String)
{
// Convert Base64 String to byte[]
byte[] imageBytes = Convert.FromBase64String(base64String);
MemoryStream ms = new MemoryStream(imageBytes, 0, imageBytes.Length);
// Convert byte[] to Image
ms.Write(imageBytes, 0, imageBytes.Length);
Image image = Image.FromStream(ms, true);
return image;
}
Front :
<Image Name="camImage"/>
Back:
public async void Base64ToImage(string base64String)
{
// read stream
var bytes = Convert.FromBase64String(base64String);
var image = bytes.AsBuffer().AsStream().AsRandomAccessStream();
// decode image
var decoder = await BitmapDecoder.CreateAsync(image);
image.Seek(0);
// create bitmap
var output = new WriteableBitmap((int)decoder.PixelHeight, (int)decoder.PixelWidth);
await output.SetSourceAsync(image);
camImage.Source = output;
}

Convert Image into ByteArray

I know there already are plenty of post about this, but every solution I have tried so far failed. What I want is to get a Byte[] from an Image object.
What I have tried so far:
using (MemoryStream ms = new MemoryStream()){/*...*/} (GDI+ Exception)
Working on a copy of the image (ArgumentNullException (Encoder))
Follow the solution from Microsoft (ArgumentNullException (Encoder))
Use an ImageConverter (GDI+ Exception)
What I expect to have:
public static Byte[] BytesFromImage(Image img) {
Byte[] imgFile;
MemoryStream ms = new MemoryStream();
img.Save(ms, img.RawFormat);
imgfile = ms.ToArray();
return imgFile;
}
Everytime I get an error, it comes from img.save(ms, img.RawFormat);.
Maybe it is just me, but all of the solution that I've followed on StackOverflow gave me the same results: a GDI+ Error with such a great explanation.
Replace img.RawFormat with ImageFormat.Bmp
Example:
class Program
{
public static byte[] BytesFromImage(Image img)
{
Byte[] imgFile;
MemoryStream ms = new MemoryStream();
img.Save(ms, ImageFormat.Bmp);
imgFile = ms.ToArray();
return imgFile;
}
private static void Main(string[] args)
{
using (Image image = new Bitmap(100, 100))
{
byte[] imgArr = BytesFromImage(image);
Console.WriteLine("Image size is: {0}", imgArr.Length);
}
}

Categories