i store my website image in form of byte array , but when i try to save them as jpeg file ,some of this file throw exception.here is my code for get image:
IList<PropertyInfo> properties = typeof(ApplicationUser).GetProperties()
.Where(x => x.PropertyType == typeof(Byte[])).ToList();
var imaBytes = property.GetValue(user, null) as Byte[];
if (imaBytes == null || imaBytes.Length == 0) continue;
Image userImage = ImageHelper.byteArrayToImage(imaBytes);
userImage.Save(pathname + $@"\{DirName}\" + property.Name + ".jpg", ImageFormat.Jpeg);
and this is my ImageHelper.byteArrayToImage :
public static Image byteArrayToImage(byte[] byteArrayIn)
{
try
{
using (MemoryStream ms = new MemoryStream(byteArrayIn))
using (var image = Image.FromStream(ms,false,true))
{
byteArrayIn = new byte[0];
return new Bitmap(image);
}
}
catch (Exception e)
{
Logger.log(e);
}
}
edit:
i wrap MemoryStream and Image code with using statment and change my code and add ImageToDisk method :
public static void ImageToDisk(byte[] byteArrayIn, string pathToSave)
{
try
{
using (MemoryStream ms = new MemoryStream(byteArrayIn))
{
using (var image = Image.FromStream(ms, false, true))
{
image.Save(pathToSave, ImageFormat.Jpeg);
image.Dispose();
}
}
}
catch (Exception e)
{
Logger.log(e);
throw;
}
}
and main code is this:
foreach (var property in properties)
{
try
{
var imaBytes = property.GetValue(user, null) as Byte[];
if (imaBytes == null || imaBytes.Length == 0)
{
continue;
}
ImageHelper.ImageToDisk(imaBytes, pathname + $@"\{DirName}\" + property.Name + ".jpg");
}
catch (Exception ex)
{
LogException(ex);
}
}
but now am getting system.runtime.interopservices.externalexception
EDIT 2:
i am completely dizzy!!! its seems some user upload images from IE and IE change MIME type to image/PJPEG

error occurred is some file with this MIME type but also some other image/PJPEG files save correctly without any exception
how can i resolve this error??
return Image.FromStream(...);instead of doing that in a using block and constructing a bitmap around it?Dispose()wasn't called on objects that need disposing, lots of temporary objects (like those created by string operations) or frequent resizing of large arrays. All these create temporary objects that will be garbage collected at some point. In the mean time though they create a lot of memory fragmentation. The runtime may not be able to find a large enough block to allocate the newbytearray or that new List