gpt4 book ai didi

c# - GDI+ 在 c# 循环中将位图保存到文件时发生一般错误

转载 作者:太空宇宙 更新时间:2023-11-03 23:46:39 26 4
gpt4 key购买 nike

我在一个循环中将位图保存到我硬盘上的一个文件中(一个目录中的所有 jpeg 文件都被保存到一个数据库中)。保存在第一次通过循环时工作正常,但在第二次通过时给出主题错误。我想也许文件被锁定了,所以我尝试为每次传递生成一个唯一的文件名,并且在文件保存后我也在位图上使用 Dispose() 。知道是什么导致了这个错误吗?

这是我的代码:

private string fileReducedDimName = @"c:\temp\Photos\test\filePhotoRedDim";
...
foreach (string file in files)
{
int i = 0;

//if the file dimensions are big, scale the file down
Stream photoStream = File.OpenRead(file);
byte[] photoByte = new byte[photoStream.Length];
photoStream.Read(photoByte, 0, System.Convert.ToInt32(photoByte.Length));
Image image = Image.FromStream(new MemoryStream(photoByte));
Bitmap bm = ScaleImage(image);
bm.Save(fileReducedDimName + i.ToString() + ".jpg", ImageFormat.Jpeg);//error occurs here
Array.Clear(photoByte,0, photoByte.Length);
bm.Dispose();

i ++;
}
...

谢谢

这是比例图像代码:(这似乎工作正常)

protected Bitmap ScaleImage(System.Drawing.Image Image)
{
//reduce dimensions of image if appropriate
int destWidth;
int destHeight;
int sourceRes;//resolution of image
int maxDimPix;//largest dimension of image pixels
int maxDimInch;//largest dimension of image inches
Double redFactor;//factor to reduce dimensions by
if (Image.Width > Image.Height)
{
maxDimPix = Image.Width;
}
else
{
maxDimPix = Image.Height;
}
sourceRes = Convert.ToInt32(Image.HorizontalResolution);
maxDimInch = Convert.ToInt32(maxDimPix / sourceRes);

//Assign size red factor based on max dimension of image (inches)
if (maxDimInch >= 17)
{
redFactor = 0.45;
}
else if (maxDimInch < 17 && maxDimInch >= 11)
{
redFactor = 0.65;
}
else if (maxDimInch < 11 && maxDimInch >= 8)
{
redFactor = 0.85;
}
else//smaller than 8" dont reduce dimensions
{
redFactor = 1;
}
destWidth = Convert.ToInt32(Image.Width * redFactor);
destHeight = Convert.ToInt32(Image.Height * redFactor);
Bitmap bm = new Bitmap(destWidth, destHeight,
PixelFormat.Format24bppRgb);
bm.SetResolution(Image.HorizontalResolution, Image.VerticalResolution);
Graphics grPhoto = Graphics.FromImage(bm);
grPhoto.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;

grPhoto.DrawImage(Image,
new Rectangle(0, 0, destWidth, destHeight),
new Rectangle(0, 0, Image.Width, Image.Height),
GraphicsUnit.Pixel);

grPhoto.Dispose();
return bm;

}

最佳答案

如果我没看错代码,你的 i 变量在每次循环中都是零。

关于c# - GDI+ 在 c# 循环中将位图保存到文件时发生一般错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27428245/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com