Image.Save method yields no result - c#

My aim is to convert a base64 string into an image and save it to the disk. I have the following code (mostly from this SO answer) -
namespace ImageSaver
{
using System;
static class Program
{
public static void LoadImage()
{
//get a temp image from bytes, instead of loading from disk
//data:image/gif;base64,
//this image is a single pixel (black)
byte[] bytes = Convert.FromBase64String("R0lGODlhAQABAIAAAAAAAAAAACH5BAAAAAAALAAAAAABAAEAAAICTAEAOw==");
Image image;
Bitmap bimage;
using (MemoryStream ms = new MemoryStream(bytes))
{
image = Image.FromStream(ms);
}
bimage = new Bitmap(image);
bimage.Save("c:\\img.gif", System.Drawing.Imaging.ImageFormat.Gif);
}
static void Main(string[] args)
{
ImageSaver.Program.LoadImage();
}
}
}
I ran it on MS Visual Studio 2010 Ultimate (Windows 8.1 Pro x64), without errors, but I could not find the image file in C drive. Where did I go wrong?

Try to save your file in this way:
File.WriteAllBytes(#"c:\img.gif", bytes);
EDIT
Anyway put your code under try'n'catch to better understand why you file is not being saved.

Try updating LoadImage to this to find out what the error is, and set a debug point on the MessageBox to examine the full details of what's happening;
public static void LoadImage()
{
try
{
//get a temp image from bytes, instead of loading from disk
//data:image/gif;base64,
//this image is a single pixel (black)
byte[] bytes = Convert.FromBase64String("R0lGODlhAQABAIAAAAAAAAAAACH5BAAAAAAALAAAAAABAAEAAAICTAEAOw==");
Image image;
Bitmap bimage;
using (MemoryStream ms = new MemoryStream(bytes))
{
image = Image.FromStream(ms);
}
bimage = new Bitmap(image);
bimage.Save("c:\\img.gif", System.Drawing.Imaging.ImageFormat.Gif);
}
catch (Exception ex) {
MessageBox.Show(ex.Message);
}
}

Related

How can i save to clipboard an image in base64?

I'm trying to save to clipboard an image in base64. But i can't find methods to do it. I can get the base64 string and save it, but not an Image :
public void GetUrl(ExportEventArgs Args)
{
string dataURL = Args.DataUrl;
//byte[] bytes = Convert.FromBase64String(dataURL);
//System.Drawing.Image image;
//using (MemoryStream ms = new MemoryStream(bytes))
//{
// image = System.Drawing.Image.FromStream(ms);
//}
Clipboard.SetTextAsync(dataURL);
}
I'm using .NET MAUI Blazor and the Clipboard class is Microsoft.Maui.ApplicationModel.DataTransfer.Clipboard but i can't find how do it.
Thanks :)

Image to byte array fails "A generic error occurred in GDI+."

let's assume I let the user choose an image from the computer. I load the file to a picture box. here is the conversion method:
public static Image LoadImageFromFile(string fileName)
{
Image result = null;
if (!File.Exists(fileName))
return result;
FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read);
try
{
using (Image image = Image.FromStream(fs))
{
ImageManipulation.RotateImageByExifOrientationData(image);
result =(Image) image.Clone();
image.Dispose();
}
}
finally
{
fs.Close();
}
return result;
}
then, when the user clicks on the Save button, I convert the image into a byte array and save it into the database. here is the conversion code:
public static byte[] ImageToByteArray(Image image)
{
if (image == null)
return null;
using (var ms = new MemoryStream())
{
ImageFormat imageFormat = image.RawFormat;
ImageCodecInfo codec = ImageCodecInfo.GetImageDecoders().FirstOrDefault(c => c.FormatID == imageFormat.Guid);
var encoderParameters = new EncoderParameters(1);
encoderParameters.Param[0] = new EncoderParameter(Encoder.Quality, 100L);
if (codec != null)
image.Save(ms, codec, encoderParameters);
else
image.Save(ms, ImageFormat.Jpeg);
return ms.ToArray();
}
}
but the problem:
I have a jpg file on the disk. I can load it into my picture box without any problem. the picture is perfectly visible in it. but when I save it, the code gives me "A generic error occurred in GDI+." Error at 'image.Save(ms, codec,encoderParameters)' line.
more odd incident: I don't get this error all the time. it is happening with specific images. for example, I downloaded an image from the internet and crop it in "Paint" and saved it as jpg. error happened. open it in Paint again and save it as png. no error!!!! that is why I am really confused . and Yes I already have tried to don't dispose the image. not helping
I know it might be a stupid question but I am desperately stuck here :)
Thank you in Advanced
I didn't find out why my code is not working but I just substitute my loading method with the code below. it is releasing the file and at the same time works as it should.
public static Image LoadImageFromFile(string fileName)
{
using (Bitmap bmb = new Bitmap(fileName))
{
MemoryStream m = new MemoryStream();
bmb.Save(m, ImageFormat.Bmp);
return Image.FromStream(m);
}
}

Why won't GDI+ save this image?

I'm trying to save a file using GDI+, but I just get a "A generic error occurred in GDI+" exception. The code works fine for almost every photo but this one (we handle thousands a day for years and this is the first I've heard of it). I think it might have something to do with exif data or perhaps something else odd from the photographers camera or editor.
Here's the photo in question
And here is code to reproduce the error with this photo:
class Program
{
static void Main(string[] args)
{
using (var img = Image.FromFile("Err.jpg"))
using (var ms = new MemoryStream())
{
img.Save(ms, ImageFormat.Jpeg);
}
}
}
How am I supposed to handle this in GDI+? Is there a way to strip out the extra stuff that is causing the problem?
It seems that converting the image to a bmp first solves the problem. It would be nice to find a method that is more efficient (doesn't require multiple images to be created and loaded into memory), but this is the best I've found so far.
static void Main(string[] args)
{
var path = #"gdi_err.jpg";
using (var img1 = Image.FromFile(path))
using (var ms1 = new MemoryStream())
{
img1.Save(ms1, ImageFormat.Bmp);
ms1.Position = 0;
using (var img2 = Image.FromStream(ms1))
using (var ms2 = new MemoryStream())
{
img2.Save(ms2, ImageFormat.Jpeg);
}
}
}
The exif profile of your image seems to be the problem. When I remove it I can save the image to the memorystream. I used Magick.NET to remove the exif profile.
using (MagickImage magickImage = new MagickImage())
{
using (var magickStream = new MemoryStream())
{
magickImage.Read(#"gdi_err.jpg");
magickImage.Strip();
magickImage.Write(magickStream);
magickStream.Position = 0;
// This part is just here to demonstrate that saving the image works.
// You don't need it because magickStream already contains the data you want.
using (Image image = Image.FromStream(magickStream))
{
using (var ms = new MemoryStream())
{
image.Save(ms, ImageFormat.Jpeg);
}
}
}
}

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);
}
}

A generic error occurred in GDI+

I loaded an image into a Picture Box using:
picturebox1.Image = Image.FromFile()
and I save it by using:
Bitmap bm = new Bitmap(pictureBox1.Image);
bm.Save(FileName, ImageFormat.Bmp);
It works perfectly fine when creating a new file, but when I try to replace the existing image, I get thrown the following runtime error:
A generic error occurred in GDI+
So what can I do to solve this problem??
That because the image file is used by your picturebox1.Image, try to save it to different file path instead:
picturebox1.Image = Image.FromFile(FileName);
Bitmap bm = new Bitmap(pictureBox1.Image);
bm.Save(#"New File Name", ImageFormat.Bmp);
Edit: You could also add a copy from the image at the first place like:
picturebox1.Image = new Bitmap(Image.FromFile(FileName));
Bitmap bm = new Bitmap(pictureBox1.Image);
bm.Save(FileName, ImageFormat.Bmp);//no error will occurs here.
The FromFile method locks the file, so use the Image.FromStream() method for reading the image:
byte[] bytes = System.IO.File.ReadAllBytes(filename);
System.IO.MemoryStream ms = new System.IO.MemoryStream(bytes);
pictureBox1.Image = Image.FromStream(ms);
Then save like you were before.
This can also happen if the path does not exist.
You could create the dir with:
System.IO.Directory.CreateDirectory(System.IO.Path.GetDirectoryName(FileName));
When either a Bitmap object or an Image object is constructed from a file, the file remains locked for the lifetime of the object. As a result, you cannot change an image and save it back to the same file where it originated. http://support.microsoft.com/?id=814675
A generic error occurred in GDI+, JPEG Image to MemoryStream:
Image.Save(..) // throws a GDI+ exception because the memory stream is closed
http://alperguc.blogspot.in/2008/11/c-generic-error-occurred-in-gdi.html
EDIT: Just writing from memory. Saving to an 'intermediary' MemoryStream should work:
For example, replace this:
Bitmap newBitmap = new Bitmap(thumbBMP);
thumbBMP.Dispose();
thumbBMP = null;
newBitmap.Save("~/image/thumbs/" + "t" + objPropBannerImage.ImageId, ImageFormat.Jpeg);
with something like:
string outputFileName = "...";
using (MemoryStream memory = new MemoryStream())
{
using (FileStream fs = new FileStream(outputFileName, FileMode.Create, FileAccess.ReadWrite))
{
thumbBMP.Save(memory, ImageFormat.Jpeg);
byte[] bytes = memory.ToArray();
fs.Write(bytes, 0, bytes.Length);
}
}
try this.
picturebox1.Image = Image.FromFile(FileName);
Bitmap bm = new Bitmat(pictureBox1.Image);
Image img = (Image)b;
img.Save(FileName, ImageFormat.Bmp);
Just like #Jalal Aldeen Saa'd said, the picture box is using the file and locked from file replacement.
//unlock file by clearing it from picture box
if (picturebox1.Image != null)
{
picturebox1.Image.Dispose();
picturebox1.Image = null;
}
//put back the picture inside the pictureBox?
try this it will work
public void SavePicture()
{
Bitmap bm = new Bitmap(this.myBitmap)
bm.Save("Output\\out.bmp" ,System.Drawing.Imaging.ImageFormat.Bmp );
}
This can also happen if you forget to add the filename:
bm.Save(#"C:\Temp\Download", System.Drawing.Imaging.ImageFormat.Png);
And can be fixed by adding the file name:
bm.Save(#"C:\Temp\Download\Image.png", System.Drawing.Imaging.ImageFormat.Png);
Note: You don't actually have to add the extension for it to work.
Try this:
private void LoadPictureBoxWithImage( string ImagePath)
{
Stream objInputImageStream = null;
BitmapData bmdImageData = null;
Bitmap bmpSrcImage = null, bmTemp = null;
byte[] arrImageBytes = null;
int bppModifier = 3;
try
{
objInputImageStream = new MemoryStream();
using (FileStream objFile = new FileStream(ImagePath, FileMode.Open, FileAccess.Read))
{
objFile.CopyTo(objInputImageStream);
}
bmpSrcImage = new Bitmap(objInputImageStream);
bppModifier = bmpSrcImage.PixelFormat == PixelFormat.Format24bppRgb ? 3 : 4;
//reda from byte[] to bitmap
bmdImageData = bmpSrcImage.LockBits(new Rectangle(0, 0, bmpSrcImage.Width, bmpSrcImage.Height), ImageLockMode.ReadOnly, bmpSrcImage.PixelFormat);
arrImageBytes = new byte[Math.Abs(bmdImageData.Stride) * bmpSrcImage.Height];
System.Runtime.InteropServices.Marshal.Copy(bmdImageData.Scan0, arrImageBytes, 0, arrImageBytes.Length);
bmpSrcImage.UnlockBits(bmdImageData);
pbSetup.Image = (Bitmap)bmpSrcImage.Clone();
pbSetup.Refresh();
}
catch (Exception ex)
{
throw new Exception("Error in Function " + System.Reflection.MethodInfo.GetCurrentMethod().Name + "; " + ex.Message);
}
finally
{
if (objInputImageStream != null)
{
objInputImageStream.Dispose();
objInputImageStream = null;
}
if (bmdImageData != null)
{
bmdImageData = null;
}
if (bmpSrcImage != null)
{
bmpSrcImage.Dispose();
bmpSrcImage = null;
}
if (bmTemp != null)
{
bmTemp.Dispose();
bmTemp = null;
}
if (arrImageBytes != null)
{
arrImageBytes = null;
}
}
}
A generic error occurred in GDI+
I also faced the same issue. I tried so many ways to fix this issue. Finally, I found a place where I have gone wrong. The problem is that I used space in the file path, which is not acceptable. Now it is working fine after removing the space in front of C after the apostrophe:
"SupplyItems":"C:\\inetpub\\HIBMS_Ver1\\BarcodeImages\\Supply\\"
instead... I used below one.
"SupplyItems":" C:\\inetpub\\HIBMS_Ver1\\BarcodeImages\\Supply\\"
Minor mistake but took a long time to find and to fix it.
Note that images created by Image.Clone() will still cause GDI+ errors as shown by the BAD code below, you must use the Image.FromStream() method for reading the image as shown in the solution on this page.
//BAD CODE: the image we will try to save AFTER the original image has been cloned and disposed
Image clonedImage;
//load image from file, clone it then dispose
using (var loadedFromDiskImage = Image.FromFile(filePath))
{
clonedImage = (Image) loadedFromDiskImage.Clone();
}
//you might think the new image can be saved given the original is disposed
//but this doesn't seem to be the way Clone() works
//expect GDI+ error in line below:
clonedImage.Save(filePath);

Categories