我尝试使用此代码调整图像大小:
ConvertToBitmap(txtImage.Text);
private void ConvertToBitmap(string filename)
{
if (File.Exists(filename))
{
var origImg = System.Drawing.Image.FromFile(filename);
var widthDivisor = (double)origImg.Width / (double)900;
var heightDivisor = (double)origImg.Height / (double)750;
int newWidth, newHeight;
if (widthDivisor < heightDivisor)
{
newWidth = (int)((double)origImg.Width / widthDivisor);
newHeight = (int)((double)origImg.Height / widthDivisor);
}
else
{
newWidth = (int)((double)origImg.Width / heightDivisor);
newHeight = (int)((double)origImg.Height / heightDivisor);
}
var newImg = new Bitmap(newWidth, newHeight);
Graphics g = Graphics.FromImage(newImg);
g.DrawImage(origImg, new Rectangle(0, 0, newWidth, newHeight));
System.Drawing.Imaging.EncoderParameters encoderParameters = new System.Drawing.Imaging.EncoderParameters(1);
encoderParameters.Param[0] = new System.Drawing.Imaging.EncoderParameter(System.Drawing.Imaging.Encoder.Quality, (long)350);
newImg.Save(fullpath, GetImageCodeInfo("image/jpeg"), encoderParameters);
g.Dispose();
}
}
public static ImageCodecInfo GetImageCodeInfo(string mimeType)
{
ImageCodecInfo[] info = ImageCodecInfo.GetImageEncoders();
foreach (ImageCodecInfo ici in info)
if (ici.MimeType.Equals(mimeType, StringComparison.OrdinalIgnoreCase))
return ici;
return null;
}
private ImageCodecInfo GetEncoder(ImageFormat format)
{
ImageCodecInfo[] codecs = ImageCodecInfo.GetImageDecoders();
foreach (ImageCodecInfo codec in codecs)
{
if (codec.FormatID == format.Guid)
{
return codec;
}
}
return null;
}
它是调整图像大小,但有些显示错误a generic error occurred in gdi+
。欢迎任何额外的努力。