0
我檢查圖像文件的大小,如果文件很大,那麼我會重新調整它的大小,以便處理速度更快。但是當我使用調整大小的代碼時,我總是得到一個指向image
的空引用異常。我試過調試 - >返回的調整大小的位圖不是null,而是轉換後的圖像>image = new Image(x);爲空。如果我刪除調整大小函數,代碼工作正常。圖片<Bgr, byte>總是返回空
Image<Bgr, byte> image = null;
foreach (string s in mylist)
{
Bitmap x = new Bitmap(Bitmap.FromFile(s));
if (x.Width > 1000 || x.Height > 1000)
{
x = ResizekeepAspectRatio(x, 1000, 1000);
image = new Image<Bgr, byte>(x);
}
else
{
image = new Image<Bgr, byte>(x);
}
work(image, x, s);
}
----------------------------------------------------------------------
Bitmap ResizekeepAspectRatio(Bitmap imgPhoto, int Width, int Height)
{
int sourceWidth = imgPhoto.Width;
int sourceHeight = imgPhoto.Height;
int sourceX = 0;
int sourceY = 0;
int destX = 0;
int destY = 0;
float nPercent = 0;
float nPercentW = 0;
float nPercentH = 0;
nPercentW = ((float)Width/(float)sourceWidth);
nPercentH = ((float)Height/(float)sourceHeight);
if (nPercentH < nPercentW)
{
nPercent = nPercentH;
destX = System.Convert.ToInt16((Width -
(sourceWidth * nPercent))/2);
}
else
{
nPercent = nPercentW;
destY = System.Convert.ToInt16((Height -
(sourceHeight * nPercent))/2);
}
int destWidth = (int)(sourceWidth * nPercent);
int destHeight = (int)(sourceHeight * nPercent);
Bitmap bmPhoto = new Bitmap(Width, Height,
PixelFormat.Format24bppRgb);
bmPhoto.SetResolution(imgPhoto.HorizontalResolution,
imgPhoto.VerticalResolution);
Graphics grPhoto = Graphics.FromImage(bmPhoto);
grPhoto.Clear(Color.Red);
grPhoto.InterpolationMode =
InterpolationMode.HighQualityBicubic;
grPhoto.DrawImage(imgPhoto,
new Rectangle(destX, destY, destWidth, destHeight),
new Rectangle(sourceX, sourceY, sourceWidth, sourceHeight),
GraphicsUnit.Pixel);
grPhoto.Dispose();
return bmPhoto;
}