【发布时间】:2018-05-05 02:19:23
【问题描述】:
我正在尝试通过调整大小将位图图像转换为 gif 图像。 例如,如果位图是 3MB,那么我希望 gif 在转换之后,例如 500x500
using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace BatchResize
{
class Program
{
static void Main(string[] args)
{
string[] array1 = Directory.GetFiles(@"C:\temp\tempVideo\MVI_8977.MOV\Lightning 0 Length 25 [48 - 73]");
foreach(string image in array1)
{
Console.WriteLine("Working on file: " + image);
Image img = ResizeImage(image, 500, 500);
img.Save(@"C:\temp\newimgs\", System.Drawing.Imaging.ImageFormat.Gif);
img.Dispose();
}
}
//Image Resize Helper Method
private static Bitmap ResizeImage(String filename, int maxWidth, int maxHeight)
{
using (Image originalImage = Image.FromFile(filename))
{
//Caluate new Size
int newWidth = originalImage.Width;
int newHeight = originalImage.Height;
double aspectRatio = (double)originalImage.Width / (double)originalImage.Height;
if (aspectRatio <= 1 && originalImage.Width > maxWidth)
{
newWidth = maxWidth;
newHeight = (int)Math.Round(newWidth / aspectRatio);
}
else if (aspectRatio > 1 && originalImage.Height > maxHeight)
{
newHeight = maxHeight;
newWidth = (int)Math.Round(newHeight * aspectRatio);
}
Bitmap newImage = new Bitmap(newWidth, newHeight);
using (Graphics g = Graphics.FromImage(newImage))
{
//--Quality Settings Adjust to fit your application
g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBilinear;
g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
g.PixelOffsetMode = System.Drawing.Drawing2D.PixelOffsetMode.HighQuality;
g.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;
g.DrawImage(originalImage, 0, 0, newImage.Width, newImage.Height);
return newImage;
}
}
}
}
}
原始图像是位图,我想调整它们的大小并将它们保存为 gif。
异常上线:
img.Save(@"C:\temp\newimgs\", System.Drawing.Imaging.ImageFormat.Gif);
System.Runtime.InteropServices.ExternalException: 'GDI+ 中出现一般错误。'
System.Runtime.InteropServices.ExternalException occurred
HResult=0x80004005
Message=A generic error occurred in GDI+.
Source=<Cannot evaluate the exception source>
StackTrace:
at System.Drawing.Image.Save(String filename, ImageCodecInfo encoder, EncoderParameters encoderParams)
at System.Drawing.Image.Save(String filename, ImageFormat format)
at BatchResize.Program.Main(String[] args) in c:\users\ccc\source\repos\BatchResize\BatchResize\Program.cs:line 21
【问题讨论】:
-
总是,还是在特定文件上?您对
Save的调用缺少文件名。也许这也是个问题。
标签: c#