[英]Graphics.DrawImage() - Throws out of memory exception
我有一些圖像,我需要做一些原始的重新尺寸工作 - 為了這個例子的目的,我只想說我需要增加給定圖像的寬度和高度4像素。 我不確定為什么調用Graphics.DrawImage()拋出一個OOM - 這里的任何建議都將非常感激。
class Program
{
static void Main(string[] args)
{
string filename = @"c:\testImage.png";
// Load png from stream
FileStream fs = new FileStream(filename, FileMode.Open);
Image pngImage = Image.FromStream(fs);
fs.Close();
// super-hacky resize
Graphics g = Graphics.FromImage(pngImage);
g.DrawImage(pngImage, 0, 0, pngImage.Width + 4, pngImage.Height + 4); // <--- out of memory exception?!
// save it out
pngImage.Save(filename, System.Drawing.Imaging.ImageFormat.Png);
}
}
我剛遇到同樣的問題。 但是修復輸出圖形的大小並沒有解決我的問題。 我意識到當我在很多圖像上使用代碼時,我試圖使用非常高的質量來繪制圖像,這會占用太多內存。
g.CompositingQuality = CompositingQuality.HighQuality;
g.InterpolationMode = InterpolationMode.HighQualityBicubic;
g.SmoothingMode = SmoothingMode.HighQuality;
在對這些行進行評論之后,代碼完美無缺。
您的圖形表面僅適用於原始大小的圖像。 您需要創建一個正確大小的新圖像,並將其用作Graphics對象的源。
Image newImage = new Bitmap(pngImage.Width + 4, pngImage.Height+4);
Graphics g = Graphics.FromImage(newImage);
這可能無法實現您希望看到的圖像與FromImage
指定的圖像大小相同,而您可以使用Bitmap
類:
using (var bmp = new Bitmap(fileName))
{
using (var output = new Bitmap(
bmp.Width + 4, bmp.Height + 4, bmp.PixelFormat))
using (var g = Graphics.FromImage(output))
{
g.DrawImage(bmp, 0, 0, output.Width, output.Height);
output.Save(outFileName, ImageFormat.Png);
}
}
你能試試這個嗎?
class Program
{
static void Main(string[] args)
{
string filename = @"c:\testImage.png";
// Load png from stream
FileStream fs = new FileStream(filename, FileMode.Open);
Image pngImage = Image.FromStream(fs);
fs.Close();
// super-hacky resize
Graphics g = Graphics.FromImage(pngImage);
pngImage = pngImage.GetThumbnailImage(image.Width, image.Height, null, IntPtr.Zero);
g.DrawImage(pngImage, 0, 0, pngImage.Width + 4, pngImage.Height + 4); // <--- out of memory exception?!
// save it out
pngImage.Save(filename, System.Drawing.Imaging.ImageFormat.Png);
}
}
靈感來自這個問題: 在調用DrawImage時幫助解決“Out of memory”異常
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.