This seems to be a bit of an infamous error all over the web. So much so that I have been unable to find an answer to my problem as my scenario doesn\'t fit. An exception ge
Save image to bitmap variable
using (var ms = new MemoryStream())
{
Bitmap bmp = new Bitmap(imageToConvert);
bmp.Save(ms, format);
return ms.ToArray();
}
My turn!
using (System.Drawing.Image img = Bitmap.FromFile(fileName))
{
... do some manipulation of img ...
img.Save(fileName, System.Drawing.Imaging.ImageFormat.Jpeg);
}
Got it on the .Save... because the using() is holding the file open, so I can't overwrite it. Maybe this will help someone in the future.
I notice that your "jpeg" case is actually:
default:
format = ImageFormat.Jpeg;
break;
Are you sure that the format is jpeg and not something else?
I'd try:
case "image/jpg": // or "image/jpeg" !
format = ImageFormat.Jpeg;
break;
Or check what imageToConvert.MimeType()
is actually returning.
UPDATE
Is there any other initialisation you need to do to the MemoryStream object?
Simple, create a new instance of Bitmap solves the problem.
string imagePath = Path.Combine(Environment.CurrentDirectory, $"Bhatti{i}.png");
Bitmap bitmap = new Bitmap(image);
bitmap.Save(imagePath);
We had a similar problem on generating a PDF
or resize image using ImageProcessor lib on production server.
Recycle the application pool fix the issue.
byte[] bts = (byte[])page1.EnhMetaFileBits;
using (var ms = new MemoryStream(bts))
{
var image = System.Drawing.Image.FromStream(ms);
System.Drawing.Image img = image.GetThumbnailImage(200, 260, null, IntPtr.Zero);
img.Save(NewPath, System.Drawing.Imaging.ImageFormat.Png);
}