原文:
上傳圖檔時,使用GDI+中重繪方式将CMYK圖檔轉為RGB圖檔我們知道,如果網站上傳圖檔時,如果使用者上傳的是CMYK圖檔,那麼在網站上将是無法顯示的,通常的現象是出現一個紅叉。
下面使用将Image重新繪制為Format24bppRgb的方式來解決此問題:
public static void SavePostedImage(HttpPostedFile postedFile, string destFileName, int maxHeight, int maxWidth)
{
System.Drawing.Imaging.ImageFormat imgFormat;
if (destFileName.ToLower().EndWith("jpg"))
{
imgFormat = ImageFormat.Jpeg;
}
else //這裡可以加更多選項,比如png,gif,tif....
imgFormat = ImageFormat.Gif;
Bitmap bmp = new Bitmap(postedFile.InputStream);
if (IsCMYK(bmp))
bmp = ConvertCMYK(bmp);
}
if ((bmp.HorizontalResolution > 72) || (bmp.VerticalResolution > 72))
bmp.SetResolution(72, 72);
Bitmap saveBmp;
if ((bmp.Height > maxHeight) || (bmp.Width > maxWidth))
Double heightRatio = Convert.ToDouble(maxHeight) / Convert.ToDouble(bmp.Height);
Double widthRatio = Convert.ToDouble(maxWidth) / Convert.ToDouble(bmp.Width);
Double scaleRatio;
if (heightRatio > widthRatio)
{
scaleRatio = widthRatio;
}
else
scaleRatio = heightRatio;
int height = Convert.ToInt32(bmp.Height * scaleRatio);
int width = Convert.ToInt32(bmp.Width * scaleRatio);
saveBmp = new Bitmap(bmp, width, height);
else
saveBmp = new Bitmap(bmp);
bmp.Dispose();
saveBmp.Save(destFileName, imgFormat);
saveBmp.Dispose();
postedFile.InputStream.Close();
}
public static string GetImageFlags(System.Drawing.Image img)
ImageFlags FlagVals = (ImageFlags)Enum.Parse(typeof(ImageFlags), img.Flags.ToString());
return FlagVals.ToString();
public static bool IsCMYK(System.Drawing.Image img)
bool isCmyk;
if ((GetImageFlags(img).IndexOf("Ycck") > -1) || (GetImageFlags(img).IndexOf("Cmyk") > -1))
{ isCmyk = true; }
{ isCmyk = false; }
return isCmyk;
public static Bitmap ConvertCMYK(Bitmap bmp)
Bitmap tmpBmp = new Bitmap(bmp.Width, bmp.Height, PixelFormat.Format24bppRgb);
Graphics g = Graphics.FromImage(tmpBmp);
g.CompositingQuality = CompositingQuality.HighQuality;
g.SmoothingMode = SmoothingMode.HighQuality;
g.InterpolationMode = InterpolationMode.HighQualityBicubic;
Rectangle rect = new Rectangle(0, 0, bmp.Width, bmp.Height);
// 将CMYK圖檔重繪一遍,此時GDI+自動将CMYK格式轉換為RGB了
g.DrawImage(bmp, rect);
Bitmap returnBmp = new Bitmap(tmpBmp);
g.Dispose();
tmpBmp.Dispose();
return returnBmp;
}
更多讨論:
(1)如何将RGB圖檔轉換為CMYK圖檔?
(2)如何将RGB圖檔轉換為索引圖檔?
(3)如何将RGB圖檔轉換為灰階/黑白線條圖檔?
(4)上述轉換如果是在WPF中,又如何進行呢?
留給讀者去思考吧.