Image.Save() throws exception "Value cannot be null./r/nParameter name: encoder" - c#

I am getting "Value cannot be null.\r\nParameter name: encoder" error while saving a Bitmap image using RawFormat.
Sample code:
class Program
{
static void Main(string[] args)
{
try
{
var image = new System.Drawing.Bitmap(500, 400);
var stream = new MemoryStream();
image.Save(stream, image.RawFormat);
}
catch (Exception exp)
{
Console.WriteLine(exp.ToString());
}
}
}
The RawFormat doesn't exist in the existing list of ImageEncoders as below code returns null.
var imageCodecInfo = ImageCodecInfo.GetImageEncoders().FirstOrDefault(codec => codec.FormatID == image.RawFormat.Guid);
Note: The image could be any type(JPEG, BMP, PNG) etc. Image.Save() should work on image.RawFormat.
RawFormat is not Bitmap type. If I Change image.RawFormat to ImageFormat.Bmp, the save operation succeeds.
Referred below links but found nothing for making it independent of image type.
Image.Save crashing: {"Value cannot be null.\r\nParameter name: encoder"}
Why is Image.Save(Stream, ImageFormat) throwing an exception?
Any suggestions are welcome.

If you load an image from disk, you can use image.RawFormat to save that image using its original format. However there is no encoder associated with an in-memory bitmap (which is what you are creating in this sample application), so you'll have to specify an image format yourself (ie. ImageFormat.Bmp).

You can use this and it will be fixed:
image.Save(stream,ImageFormat.Jpeg);

Related

Periodically getting "A generic error occurred in GDI+"

I will appreciate any help. This is a very famous issue, but whatever I read and tried to apply to my specific case, it did not help.
I have a simple function, which takes an image as a base64 string and saves it as a png image. The destination folder is constant. The filename is taken from the imageUrl parameter and is made unique before saving.
public static void SaveWorkOrderImage(string imageData, string imageUrl)
{
try
{
//convert png image saved in a base64 string to Image object
imageData = imageData.Replace("data:image/png;base64,", "");
byte[] bytes = Convert.FromBase64String(imageData);
//...
//some code here which generates the destination path for the new image
//...
using (MemoryStream ms = new MemoryStream(bytes))
{
using (System.Drawing.Image newData = System.Drawing.Image.FromStream(ms))
{
using (Bitmap bmpData = new Bitmap(newData))
{
bmpData.Save(destPath, ImageFormat.Png);
}
}
}
}
catch (Exception ex)
{
//processing and logging exception
}
}
This code runs just fine as MVC application in IIS. But suddenly in about a week of perfect working it starts throwing the following exception for every image that is saved:
Exception Type: System.Runtime.InteropServices.ExternalException
Exception: A generic error occurred in GDI+.
Stack Trace:
at System.Drawing.Image.Save(String filename, ImageCodecInfo encoder, EncoderParameters encoderParams)
at System.Drawing.Image.Save(String filename, ImageFormat format)
If I restart the App Pool, then it again works normally for several days. Usually about a week. Then everything repeats again. It looks like some resources are not being disposed, or there is an overflow of some buffer. But, as you can see, there is a "using" statement for each disposable object.
I also tried to convert it first to a Bitmap (I found such an advise in the similar question). It looked like this before:
using (MemoryStream ms = new MemoryStream(bytes))
{
using (System.Drawing.Image newData = System.Drawing.Image.FromStream(ms))
{
newData.Save(destPath, ImageFormat.Png);
}
}
It did not help however.

C# Insert Image to Mysql [duplicate]

I am getting "Value cannot be null.\r\nParameter name: encoder" error while saving a Bitmap image using RawFormat.
Sample code:
class Program
{
static void Main(string[] args)
{
try
{
var image = new System.Drawing.Bitmap(500, 400);
var stream = new MemoryStream();
image.Save(stream, image.RawFormat);
}
catch (Exception exp)
{
Console.WriteLine(exp.ToString());
}
}
}
The RawFormat doesn't exist in the existing list of ImageEncoders as below code returns null.
var imageCodecInfo = ImageCodecInfo.GetImageEncoders().FirstOrDefault(codec => codec.FormatID == image.RawFormat.Guid);
Note: The image could be any type(JPEG, BMP, PNG) etc. Image.Save() should work on image.RawFormat.
RawFormat is not Bitmap type. If I Change image.RawFormat to ImageFormat.Bmp, the save operation succeeds.
Referred below links but found nothing for making it independent of image type.
Image.Save crashing: {"Value cannot be null.\r\nParameter name: encoder"}
Why is Image.Save(Stream, ImageFormat) throwing an exception?
Any suggestions are welcome.
If you load an image from disk, you can use image.RawFormat to save that image using its original format. However there is no encoder associated with an in-memory bitmap (which is what you are creating in this sample application), so you'll have to specify an image format yourself (ie. ImageFormat.Bmp).
You can use this and it will be fixed:
image.Save(stream,ImageFormat.Jpeg);

Overwrite image picturebox in C#

I'm doing one application,
i add a picturebox to add image to some products, i have one question, i would like edit the images already added to one product, how can i do that?
This is my actually code.
private void pbImagenEquipo_DoubleClick(object sender, EventArgs e)
{
ofdImagenes.Filter = "Imagenes JPG (*.jpg)|*.jpg; *.jpeg;|Imagenes PNG (*.png)|*.png";
DialogResult resp = ofdImagenes.ShowDialog();
if (resp == DialogResult.OK)
{
Bitmap b = new Bitmap(ofdImagenes.FileName);
string [] archivo = ofdImagenes.FileName.Split('.');
nombre = "Equipo_" + lbID+ "." + archivo[archivo.Length-1];
b.Save(Path.Combine(Application.StartupPath, "Imagenes", nombre));
pbImagenEquipo.Image = b;
}
}
But when i try to replace the image i got this error:
An unhandled exception of type 'System.Runtime.InteropServices.ExternalException' occurred in System.Drawing.dll
Additional information: Error generoc in e GDI+.
This is a common issue.
The documentation says:
Saving the image to the same file it was constructed from is not
allowed and throws an exception.
There are two options. One is to delete the file before writing it.
The other is to use a Stream to write it. I prefer the latter..:
string fn = "d:\\xyz.jpg";
// read image file
Image oldImg = Image.FromFile(fn);
// do something (optional ;-)
((Bitmap)oldImg).SetResolution(123, 234);
// save to a memorystream
MemoryStream ms = new MemoryStream();
oldImg.Save(ms, ImageFormat.Jpeg);
// dispose old image
oldImg.Dispose();
// save new image to same filename
Image newImage = Image.FromStream(ms);
newImage.Save(fn);
Note that saving jpeg files often achieves better quality if you take control of encoding options. Use this overload for this..
Also note that since we need to dispose of the image you need to make sure that it is not used anywhere, like in a PictureBox.Image! If it is, set it to null there before disposing : pictureBox1.Image = null; !
For a solution deleting the old file see here

argumentnullexception bitmap save to memorystream

I'm trying to save my Bitmap to MemoryStream - what wrong in this code? Why it gets me argumentnullexception ??
private void insertBarCodesToPDF(Bitmap barcode)
{
.......
MemoryStream ms = new MemoryStream();
barcode.Save(ms, System.Drawing.Imaging.ImageFormat.MemoryBmp); //<----
byte [] qwe = ms.ToArray();
.......
}
UPD: StackTrace
System.Drawing.Image.Save(Stream stream, ImageCodecInfo encoder, EncoderParameters encoderParams)
in WordTest.FormTestWord.insertBarCodesToPDF(Bitmap barcode)
I believe that your problem is related to the type of image you are trying to save to the MemoryStream as. According to this Code Project article: Dynamically Generating Icons (safely), some of the ImageFormat types do not have the necessary encoder to allow the Save function to save as that type.
I ran the following to determine which types did and didn't work:
System.Drawing.Bitmap b = new Bitmap(10, 10);
foreach (ImageFormat format in new ImageFormat[]{
ImageFormat.Bmp,
ImageFormat.Emf,
ImageFormat.Exif,
ImageFormat.Gif,
ImageFormat.Icon,
ImageFormat.Jpeg,
ImageFormat.MemoryBmp,
ImageFormat.Png,
ImageFormat.Tiff,
ImageFormat.Wmf})
{
Console.Write("Trying {0}:", format);
MemoryStream ms = new MemoryStream();
bool success = true;
try
{
b.Save(ms, format);
}
catch (Exception)
{
success = false;
}
Console.WriteLine("\t{0}", (success ? "works" : "fails"));
}
This gave the results of:
Trying Bmp: works
Trying Emf: fails
Trying Exif: fails
Trying Gif: works
Trying Icon: fails
Trying Jpeg: works
Trying MemoryBMP: fails
Trying Png: works
Trying Tiff: works
Trying Wmf: fails
There is a Microsoft KB Article which states that some of the ImageFormat types are read-only.

Generic exception when trying to save uploaded image file

When trying to save an uploaded file, I get this error and are having some difficulties solving it:
ExternalException: A generic error occurred in GDI+.
It's a very specific exception message!
This is my code.
// Gets the original image.
byte[] original = new byte[file.InputStream.Length];
file.InputStream.Position = 0;
file.InputStream.Read(original, 0, (int)file.InputStream.Length);
// Redimensions the original image and saves it for each of the desired pictures classes.
foreach (ClassDetails c in picturesClasses)
{
byte[] resized = Images.Resize(original, new Size(c.Width, c.Height), c.ResizeToExactProportions);
MemoryStream stream = new MemoryStream(resized);
Image resizedImage = Image.FromStream(stream);
uniqueFilename = string.Format("{0}{1}{2}", Path.GetFileNameWithoutExtension(file.FileName), Guid.NewGuid().ToString(), ".png");
// The exception happens HERE **************************************************
resizedImage.Save(Path.Combine(c.Path, uniqueFilename), ImageFormat.Png);
}
Please, any idea of what could be wrong? Thanks.
Mmm... I love it when problems are solved fast!
The path I had was a relative one. I had to use the Server.MapPath method. See below:
resizedImage.Save(HttpContext.Current.Server.MapPath(Path.Combine(c.Path, uniqueFilename)), ImageFormat.Png);

Categories

Resources