We know that if the site upload pictures, if the user uploaded a CMYK image, then the site will not be displayed, the usual phenomenon is a red fork.
The following is used to redraw the image to Format24bpprgb to resolve the problem:
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//Here can add more options, such as 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;}
Else
{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);
Redraw the CMYK picture again, when GDI + automatically converts the CMYK format to RGB
G.drawimage (BMP, Rect);
Bitmap returnbmp = new Bitmap (tmpbmp);
G.dispose ();
Tmpbmp.dispose ();
Bmp. Dispose ();
return returnbmp;
}
More discussion:
(1) How to convert RGB pictures to CMYK pictures?
(2) How to convert an RGB picture to an indexed picture?
(3) How to convert RGB picture to grayscale/black and white line picture?
(4) What if the above conversion is in WPF?
Leave it to the reader to think.