我不断收到System.Runtime.InteropServices.ExternalException'的错误。在第70行" img3.Save(finalImage,System.Drawing.Imaging.ImageFormat.Jpeg);"。最初我有一个程序,将两张照片拼接在一起工作正常,但我希望这两张图片尺寸相同(300像素,300像素),所以我插入了一个方法:
public static Image resizeImage(Image imgToResize, Size size)
{
return (Image)(new Bitmap(imgToResize, size));
}
并在我的CombineImages方法中输入:
img = resizeImage(img, new Size(300, 300));
但现在我收到了一个错误。这是我的代码:
private void cmdCombine_Click(object sender, EventArgs e)
{
//Change the path to location where your images are stored.
DirectoryInfo directory = new DirectoryInfo(@"C:\Users\Elder Zollinger\Desktop\Images");
if (directory != null)
{
FileInfo[] files = directory.GetFiles();
CombineImages(files);
}
}
private void CombineImages(FileInfo[] files)
{
//change the location to store the final image.
string finalImage = @"C:\Users\Elder Zollinger\Desktop\Images\Final.jpg";
List<int> imageHeights = new List<int>();
int nIndex = 0;
int width = 0;
foreach (FileInfo file in files)
{
Image img = Image.FromFile(file.FullName);
img = resizeImage(img, new Size(300, 300));
imageHeights.Add(img.Height);
width += img.Width;
img.Dispose();
}
imageHeights.Sort();
int height = imageHeights[imageHeights.Count - 1];
Bitmap img3 = new Bitmap(width, height);
Graphics g = Graphics.FromImage(img3);
g.Clear(SystemColors.AppWorkspace);
foreach (FileInfo file in files)
{
Image img = Image.FromFile(file.FullName);
if (nIndex == 0)
{
g.DrawImage(img, new Point(0, 0));
nIndex++;
width = img.Width;
}
else
{
g.DrawImage(img, new Point(width, 0));
width += img.Width;
}
img.Dispose();
}
g.Dispose();
img3.Save(finalImage, System.Drawing.Imaging.ImageFormat.Jpeg);
img3.Dispose();
imageLocation.Image = Image.FromFile(finalImage);
}
public static Image resizeImage(Image imgToResize, Size size)
{
return (Image)(new Bitmap(imgToResize, size));
}
}
}
答案 0 :(得分:1)
上传图片的图片格式可能无法直接转换为Jpeg。调整大小时我们做的一件事实际上是将图像绘制到新的Graphics
实例,如下所示。请注意,前两行尝试直接从原始图像实例获取像素和图像格式 - 您可能会遇到CMYK问题和带透明层(GIF / PNG)的图像。
var pixelFormat = imgToResize.PixelFormat;
var imageFormat = imgToResize.RawFormat;
Bitmap b = new Bitmap(newWidth.Value, newHeight.Value, pixelFormat);
Graphics g = Graphics.FromImage(b);
g.SmoothingMode = SmoothingMode.AntiAlias;
g.InterpolationMode = InterpolationMode.HighQualityBicubic;
g.PixelOffsetMode = PixelOffsetMode.HighQuality;
g.DrawImage(imgToResize, (float)-0.5, (float)-0.5, newWidth.Value + 1, newHeight.Value + 1);
g.Dispose();
b.Save(stream, imageFormat);