我有以下类似的函数:
// Convert To JPG
//
public string AlltoJPG(FileInfo foo)
{
// Get file extension
string fileExtension = foo.Extension;
// Get file name without extenstion
string fileName = foo.Name.Replace(foo.Extension, string.Empty) + ".jpg";
/*------------------------------------------------------------------------*/
/// <Check for PNG File Format>
if (fileExtension == ".png" || fileExtension == ".PNG")
{
System.Drawing.Image img = System.Drawing.Image.FromFile(foo.FullName);
// Assumes img is the PNG you are converting
using (Bitmap b = new Bitmap(img.Width, img.Height))
{
using (System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(b))
{
g.Clear(System.Drawing.Color.White);
g.DrawImageUnscaled(img, 0, 0);
}
// Save the image as a JPG
b.Save(fileName, System.Drawing.Imaging.ImageFormat.Jpeg);
}
}
/*------------------------------------------------------------------------*/
/// <Check for GIF File Format>
if (fileExtension == ".gif" || fileExtension == ".GIF")
{
System.Drawing.Image img = System.Drawing.Image.FromFile(foo.FullName);
// Construct a bitmap from the image resource.
Bitmap bmp1 = new Bitmap(img.Width, img.Height);
// Save the image as a JPG
bmp1.Save(fileName, System.Drawing.Imaging.ImageFormat.Jpeg);
}
/*------------------------------------------------------------------------*/
/// <Check for BMP File Format>
if (fileExtension == ".bmp" || fileExtension == ".BMP")
{
System.Drawing.Image img = System.Drawing.Image.FromFile(foo.FullName);
// Construct a bitmap from the image resource.
Bitmap bmp1 = new Bitmap(img.Width, img.Height);
// Save the image as a JPG
bmp1.Save(fileName, System.Drawing.Imaging.ImageFormat.Jpeg);
}
/*------------------------------------------------------------------------*/
/// <Check for TIFF File Format>
if (fileExtension == ".tiff" || fileExtension == ".TIFF")
{
System.Drawing.Image img = System.Drawing.Image.FromFile(foo.FullName);
// Construct a bitmap from the image resource.
Bitmap bmp1 = new Bitmap(img.Width, img.Height);
// Save the image as a JPG
bmp1.Save(fileName, System.Drawing.Imaging.ImageFormat.Jpeg);
}
/*------------------------------------------------------------------------*/
fileName = foo.DirectoryName + "\\" + fileName;
return fileName;
}
我试图将 bmp
,png
,gif
,tiff
文件格式转换为 jpg
,但是使用 GDI+
时会报错:
System.OutOfMemoryException was unhandled
Message=Bellek yetersiz.
Source=System.Drawing
StackTrace:
konum: System.Drawing.Image.FromFile(String filename, Boolean useEmbeddedColorManagement)
konum: System.Drawing.Image.FromFile(String filename)
那么我该如何避免这种情况并将至少 PNG
和 BMP
文件转换为 JPG
呢?
下面是出现错误的图片:
OriginalImage
的变量。 - Shai