[英]How can i resize images by selecting/changing the images kb ? And not resolution
[英]Getting externalexception when trying to resize images. How can I resolve it?
我正在嘗試通過調整大小將位圖圖像轉換為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
要保存圖片,您需要指定文件名而不是目錄
img.Save(@"C:\[New File Name]", ImageFormat.Gif);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.