C # cropping, scaling, sharpness, watermark handling Example _c# tutorial

Source: Internet
Author: User
Tags create directory file size transparent image

Objective

Requirements are derived from some applications in the project, such as photo album features, usually when users upload photos, we will regenerate a thumbnail for the photo, for the list on the other pages to display. A casual look, most of the site is basically the original image, such as scaling to generate thumbnails. But the perfectionist will find some problems, such as the display of typesetting to make the photo thumbnail list is very uniform, neat, and beautiful, such as requiring each thumbnail size fixed to x 90 and do not stretch deformation how to do? How can a user avatar make a thumbnail more clear than the original image? Or how to add a translucent logo watermark under the uploaded image?

OK, this article according to their own project code to describe the solution to the above problems, all based on the. Net Framework class Library Complete, the code contains some of the basic knowledge of C # image processing, share with you, personal capacity is limited, deficiencies also please correct.

Improve thumbnail clarity

(Artwork 200*200,12.3k) (after processing 80*80,17.7k)

I always thought that the thumbnail could not be clearer than the original image, until one day a product colleague showed me the effect of a website. So I started looking. NET implementation code, a closer look at the thumbnail is a bit clearer than the original, but the cost is that the thumbnail file is larger than the original, so if you want to make a large picture of the screen full of the monitor clearer, then the picture takes up space and network traffic must be considered, if it is Internet applications, It is recommended that you use this method within 200 pixels of the thumbnail. Of course, if you have better code that can make the picture file size change is not large and make the picture clearer also please share.

Picture cropping

(Artwork 256*192) (Crop requirements 100*100)

(Artwork 256*192) (Crop requirements 90*120)

(Artwork 256*192) (Crop requirements 120*90)

(Artwork 146*256) (Crop requirements 100*100)

(Artwork 146*256) (Crop requirements 90*120)

(Artwork 146*256) (Crop requirements 120*90)

Algorithm: The original image center as the cutting Center, the largest range of the original image to crop, and then to crop the result of scaling.

Picture watermark

Only shows the effect, such as changing the font, watermark transparency, location, and so on, to expand in your code or method.

Using System;
Using System.Collections.Generic;
Using System.Text;
Using System.IO;
Using System.Drawing;
Using System.Drawing.Drawing2D;

Using System.Drawing.Imaging;
 namespace Wujian.common {///<summary>///image processing///http://www.cnblogs.com/wu-jian///////Wu Jian 2011-02-20 created
  Wu Jian 2012-08-08 Modified///</summary> public class Image {#region square cropping and scaling///<summary>///square cropping Take the center of the picture as the axis, intercept the square, and then zoom///for Avatar///</summary>///<remarks> Wu Jian 2012-08-08</remarks>///&L T;param name= "FromFile" > Original Stream object </param>///<param name= "Filesaveurl" > Thumbnail store address </param>///& Lt;param name= "side" > Specified edges (square) </param>///<param name= "Quality" > Quality (Range 0-100) </param> public  static void Cutforsquare (System.IO.Stream fromfile, string filesaveurl, int side, int quality) {//Create directory string dir
   = Path.getdirectoryname (Filesaveurl); if (! Directory.Exists (dir)) directory.createdirectory (dir);

   Original picture (Gets the original picture creation object and uses the color management information embedded in the stream) System.Drawing.Image initimage = System.Drawing.Image.FromStream (FromFile, True)

   ; The original image width and height are less than the template, not processed, directly save if (Initimage.width <= side && initimage.height <= side) {Initimage.save (fi
   Lesaveurl, System.Drawing.Imaging.ImageFormat.Jpeg);
    else {///the wide, high int initwidth = Initimage.width of the original picture;

    int initheight = Initimage.height;
     The non-square type is first cropped to the square if (initwidth!= initheight) {//screenshot object System.Drawing.Image pickedimage = null;

     System.Drawing.Graphics pickedg = null; Wide and high horizontal figure if (Initwidth > Initheight) {//object instantiation Pickedimage = new System.Drawing.Bitmap (initheigh
      T, Initheight);
      PICKEDG = System.Drawing.Graphics.FromImage (pickedimage);
      Set quality Pickedg.interpolationmode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
      Pickedg.smoothingmode = System.Drawing.Drawing2D.SmoothingMode.HighQuality; Positioning RectangleFROMR = new Rectangle (initwidth-initheight)/2, 0, Initheight, initheight);
      Rectangle ToR = new Rectangle (0, 0, initheight, initheight);
      Paint Pickedg.drawimage (Initimage, ToR, FROMR, System.Drawing.GraphicsUnit.Pixel);
     Reset wide initwidth = initheight;
      ///tall and wide vertical figure else {//object instantiation Pickedimage = new System.Drawing.Bitmap (initwidth, initwidth);
      PICKEDG = System.Drawing.Graphics.FromImage (pickedimage);
      Set quality Pickedg.interpolationmode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
      Pickedg.smoothingmode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
      Positioning Rectangle FROMR = new Rectangle (0, (initheight-initwidth)/2, initwidth, initwidth);
      Rectangle ToR = new Rectangle (0, 0, initwidth, initwidth);
      Paint Pickedg.drawimage (Initimage, ToR, FROMR, System.Drawing.GraphicsUnit.Pixel);
     Resetting high initheight = Initwidth; ////To assign the screenshot object to the original INITimage = (System.Drawing.Image) pickedimage.clone ();
     Release screenshot resource Pickedg.dispose ();
    Pickedimage.dispose ();
    }//Thumbnail object System.Drawing.Image resultimage = new System.Drawing.Bitmap (side, side);
    System.Drawing.Graphics RESULTG = System.Drawing.Graphics.FromImage (resultimage);
    Set quality Resultg.interpolationmode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
    Resultg.smoothingmode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
    Clears the canvas resultg.clear (color.white) with the specified background color; Draw thumbnails Resultg.drawimage (Initimage, New System.Drawing.Rectangle (0, 0, side, side), new System.Drawing.Rectangle (0, 0

    , Initwidth, Initheight), System.Drawing.GraphicsUnit.Pixel);
    Key quality control//Get system encoding type array, contains Jpeg,bmp,png,gif,tiff imagecodecinfo[] icis = Imagecodecinfo.getimageencoders ();
    ImageCodecInfo ici = null; foreach (ImageCodecInfo i in ICIS) {if (I.mimetype = "Image/jpeg" | | i.mimetype = "Image/bmp" | | i.mimetype = = "Image/png" | |
     I.mimetype = = "Image/gif") {ici = i;
    } encoderparameters EP = new EncoderParameters (1); Ep.

    Param[0] = new Encoderparameter (System.Drawing.Imaging.Encoder.Quality, (long) Quality);

    Save thumbnail image Resultimage.save (Filesaveurl, ICI, EP); Release the resource EP for critical quality control.

    Dispose ();
    Release thumbnail resource resultg.dispose ();

    Resultimage.dispose ();
   Release the original picture Resource Initimage.dispose (); #endregion #region Custom cropping and scaling///<summary>///Specifies a long width cropping///a cropped picture of the largest scale and scaling to the template size///</summar  y>///<remarks> Wu Jian 2012-08-08</remarks>///<param name= "FromFile" > Original Stream object </param>/// <param name= "Filesaveurl" > Save path </param>///<param name= "MaxWidth" > Max width (unit: px) </param>///
  ;p Aram Name= "MaxHeight" > Max height (unit: px) </param>///<param name= "Quality" > Quality (range 0-100) </param> public static void Cutforcustom (System.IO.Stream fromfile, string filesaveurl, int maxwidth, int maxheight, int quality) {//Get the original picture from the file and use the color management information embedded in the stream System.Drawing.Image Initimage = system.drawing.image.f

   Romstream (FromFile, true); The original image width and height are less than the template, not processed, directly save if (initimage.width <= maxwidth && initimage.height <= maxheight) {Initimag
   E.save (Filesaveurl, System.Drawing.Imaging.ImageFormat.Jpeg);
    else {//stencil's wide-high proportion double templaterate = (double) maxwidth/maxheight;

    The width and height ratio of the original picture double initrate = (double) initimage.width/initimage.height; The original image is equal to the template ratio, direct scaling if (templaterate = = initrate) {//The final picture is generated by stencil size System.Drawing.Image templateimage = new
     System.Drawing.Bitmap (MaxWidth, maxheight);
     System.Drawing.Graphics Templateg = System.Drawing.Graphics.FromImage (templateimage);
     Templateg.interpolationmode = System.Drawing.Drawing2D.InterpolationMode.High;
     Templateg.smoothingmode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
     Templateg.clear (Color.White); Templateg.drawimage (InitiMage, New System.Drawing.Rectangle (0, 0, MaxWidth, maxheight), new System.Drawing.Rectangle (0, 0, Initimage.width,
     initimage.height), System.Drawing.GraphicsUnit.Pixel);
    Templateimage.save (Filesaveurl, System.Drawing.Imaging.ImageFormat.Jpeg);
     //original and template scale, after cropping else {//crop object System.Drawing.Image pickedimage = null;

     System.Drawing.Graphics pickedg = null;

     Positioning Rectangle FROMR = new Rectangle (0, 0, 0, 0);//original cut positioning Rectangle ToR = new Rectangle (0, 0, 0, 0);//target positioning Width for standard cropping if (Templaterate > Initrate) {//cropping object instantiation Pickedimage = new System.Drawing.Bitmap (init
      Image.width, (int) System.Math.Floor (initimage.width/templaterate));

      PICKEDG = System.Drawing.Graphics.FromImage (pickedimage);
      Clipping source Location fromr.x = 0;
      FROMR.Y = (int) System.Math.Floor ((initimage.height-initimage.width/templaterate)/2);
      Fromr.width = Initimage.width; Fromr.height = (int) System.Math.Floor (initimage.

      Width/templaterate);
      Cutting target positioning tor.x = 0;
      TOR.Y = 0;
      Tor.width = Initimage.width;
     Tor.height = (int) System.Math.Floor (initimage.width/templaterate);  //high for standard cropping else {pickedimage = new System.Drawing.Bitmap (int) System.Math.Floor (Initimage.height *
      templaterate), initimage.height);

      PICKEDG = System.Drawing.Graphics.FromImage (pickedimage);
      fromr.x = (int) System.Math.Floor (initimage.width-initimage.height * templaterate)/2);
      FROMR.Y = 0;
      Fromr.width = (int) System.Math.Floor (initimage.height * templaterate);

      Fromr.height = Initimage.height;
      tor.x = 0;
      TOR.Y = 0;
      Tor.width = (int) System.Math.Floor (initimage.height * templaterate);
     Tor.height = Initimage.height;
     }//Set quality Pickedg.interpolationmode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;

     Pickedg.smoothingmode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
  Cutting   Pickedg.drawimage (Initimage, ToR, FROMR, System.Drawing.GraphicsUnit.Pixel);
     Generate final picture by stencil size System.Drawing.Image templateimage = new System.Drawing.Bitmap (maxwidth, maxheight);
     System.Drawing.Graphics Templateg = System.Drawing.Graphics.FromImage (templateimage);
     Templateg.interpolationmode = System.Drawing.Drawing2D.InterpolationMode.High;
     Templateg.smoothingmode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
     Templateg.clear (Color.White); Templateg.drawimage (Pickedimage, New System.Drawing.Rectangle (0, 0, MaxWidth, maxheight), new

     System.Drawing.Rectangle (0, 0, Pickedimage.width, pickedimage.height), System.Drawing.GraphicsUnit.Pixel);
     Key quality control//Get system encoding type array, contains Jpeg,bmp,png,gif,tiff imagecodecinfo[] icis = Imagecodecinfo.getimageencoders ();
     ImageCodecInfo ici = null; foreach (ImageCodecInfo i in ICIS) {if (I.mimetype = "Image/jpeg" | | i.mimetype = "Image/bmp" | | i.mimetype = = "Image/png" | | I.mimetype == "Image/gif") {ici = i;
     } encoderparameters EP = new EncoderParameters (1); Ep.

     Param[0] = new Encoderparameter (System.Drawing.Imaging.Encoder.Quality, (long) Quality);
     Save thumbnail image Templateimage.save (Filesaveurl, ICI, EP);

     Templateimage.save (Filesaveurl, System.Drawing.Imaging.ImageFormat.Jpeg);
     Releasing resources templateg.dispose ();

     Templateimage.dispose ();
     Pickedg.dispose ();
    Pickedimage.dispose ();
  }//Release resource initimage.dispose (); #endregion #region ratio scaling///<summary>///picture scaling///</summary>///<remarks> Wu Jian 2012-08- 08</remarks>///<param name= "FromFile" > Original Stream object </param>///<param name= "Savepath" > Thumbnail store address </param>///<param name= "targetwidth" > Specified maximum width </param>///<param name= "Targetheight" > Specified maximum height </param>///<param name= "Watermarktext" > Watermark text (for "" means no watermark) </param>///<param name= " WatermarkimaGE "> Watermark picture Path (for" "means no watermark) </param> public static void Zoomauto (System.IO.Stream fromfile, string savepath, System .  Double Targetwidth, System.Double targetheight, String watermarktext, String watermarkimage) {//Create directory string dir =
   Path.getdirectoryname (Savepath); if (!

   Directory.Exists (dir)) directory.createdirectory (dir);

   The original picture (gets the original picture creation object and uses the color management information embedded in the stream) System.Drawing.Image initimage = System.Drawing.Image.FromStream (FromFile, true);
    The original image width and height are less than the template, not processed, directly save if (initimage.width <= targetwidth && initimage.height <= targetheight) { Text watermark if (watermarktext!= "") {using (System.Drawing.Graphics Gwater = System.Drawing.Graphics.FromImage (i
      Nitimage)) {System.Drawing.Font fontwater = new Font ("bold", 10);
      System.Drawing.Brush brushwater = new SolidBrush (color.white);
      Gwater.drawstring (Watermarktext, Fontwater, Brushwater, 10, 10);
     Gwater.dispose (); }///Transparent Image watermark if (WatermarkimaGE!= "") {if (file.exists (watermarkimage)) {//Get watermark Picture using (System.Drawing.Image wrimage = Sy Stem. Drawing.Image.FromFile (Watermarkimage)) {//Watermark drawing condition: The original picture is wider than or equal to the watermark picture if (Initimage.width >= wrimage.

        Width && initimage.height >= wrimage.height) {Graphics gwater = graphics.fromimage (initimage);
        Transparent properties ImageAttributes imgattributes = new ImageAttributes ();
        ColorMap ColorMap = new ColorMap ();
        Colormap.oldcolor = Color.FromArgb (255, 0, 255, 0);
        Colormap.newcolor = Color.FromArgb (0, 0, 0, 0);
        Colormap[] remaptable = {ColorMap};

        Imgattributes.setremaptable (remaptable, Coloradjusttype.bitmap); Float[][] colormatrixelements = {new float[] {1.0f, 0.0f, 0.0f, 0.0f, 0.0f}, new float[] {0.0f, 1.0f, 0.0f, 0.0f, 0.0f}, new float[] {0.0f, 0.0f, 1.0f, 0.0f, 0.0f}, new float[] {0.0f, 0.0f, 0.0f, 0.5f, 0.0f
      },//Transparency: 0.5   New float[] {0.0f, 0.0f, 0.0f, 0.0f, 1.0f}};
        ColorMatrix Wmcolormatrix = new ColorMatrix (colormatrixelements);
        Imgattributes.setcolormatrix (Wmcolormatrix, Colormatrixflag.default, Coloradjusttype.bitmap); Gwater.drawimage (Wrimage, New Rectangle (Initimage.width-wrimage.width, Initimage.height-wrimage.height,

        Wrimage.width, Wrimage.height), 0, 0, wrimage.width, Wrimage.height, GraphicsUnit.Pixel, imgattributes);
       Gwater.dispose ();
      } wrimage.dispose ();
   }}//Save Initimage.save (Savepath, System.Drawing.Imaging.ImageFormat.Jpeg);
    else {//thumbnail width, high compute double newwidth = initimage.width;

    Double newheight = initimage.height; Wide to high or wide equal to high (horizontal or square) if (Initimage.width > Initimage.height | | | initimage.width = = initimage.height) {//if lenient
      In the template if (Initimage.width > Targetwidth) {//wide press template, high scaling newwidth = Targetwidth; Newheight = Initimage.height *(Targetwidth/initimage.width); }//Hucquan (vertical) Else {//if taller than template if (Initimage.height > Targetheight) {//High press template, width proportional
      Zoom newheight = targetheight;
     Newwidth = Initimage.width * (targetheight/initimage.height); Create a new map//new BMP picture System.Drawing.Image newimage = new System.Drawing.Bitmap ((int) newwidth, (int) NEWH
    eight);

    Create a new artboard System.Drawing.Graphics NEWG = System.Drawing.Graphics.FromImage (newimage);
    Set quality Newg.interpolationmode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;

    Newg.smoothingmode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
    Background color newg.clear (color.white); Paint Newg.drawimage (initimage, New System.Drawing.Rectangle (0, 0, Newimage.width, newimage.height), new System.Drawing .

    Rectangle (0, 0, Initimage.width, initimage.height), System.Drawing.GraphicsUnit.Pixel); Text watermark if (watermarktext!= "") {using (System.drawIng.  Graphics gwater = System.Drawing.Graphics.FromImage (newimage)) {System.Drawing.Font fontwater = new Font ("Arial")
      10);
      System.Drawing.Brush brushwater = new SolidBrush (color.white);
      Gwater.drawstring (Watermarktext, Fontwater, Brushwater, 10, 10);
     Gwater.dispose ();
      }//Transparent picture watermark if (watermarkimage!= "") {if (file.exists (watermarkimage)) {//Get watermark Picture using (System.Drawing.Image wrimage = System.Drawing.Image.FromFile (watermarkimage)) {//Watermark drawing condition: The original picture is wider than or equal to to watermark image if (newimage.width >= wrimage.width && newimage.height >= wrimage.height) {Grap

        Hics gwater = Graphics.fromimage (newimage);
        Transparent properties ImageAttributes imgattributes = new ImageAttributes ();
        ColorMap ColorMap = new ColorMap ();
        Colormap.oldcolor = Color.FromArgb (255, 0, 255, 0);
        Colormap.newcolor = Color.FromArgb (0, 0, 0, 0);
    Colormap[] remaptable = {ColorMap};    Imgattributes.setremaptable (remaptable, Coloradjusttype.bitmap); Float[][] colormatrixelements = {new float[] {1.0f, 0.0f, 0.0f, 0.0f, 0.0f}, new float[] {0.0f, 1.0f, 0.0f, 0.0f, 0.0f}, new float[] {0.0f, 0.0f, 1.0f, 0.0f, 0.0f}, new float[] {0.0f, 0.0f, 0.0f, 0.5f, 0.0f

        },//Transparency: 0.5 new float[] {0.0f, 0.0f, 0.0f, 0.0f, 1.0f}};
        ColorMatrix Wmcolormatrix = new ColorMatrix (colormatrixelements);
        Imgattributes.setcolormatrix (Wmcolormatrix, Colormatrixflag.default, Coloradjusttype.bitmap); Gwater.drawimage (Wrimage, New Rectangle (Newimage.width-wrimage.width, Newimage.height-wrimage.height,
        Wrimage.width, Wrimage.height), 0, 0, wrimage.width, Wrimage.height, GraphicsUnit.Pixel, imgattributes);
       Gwater.dispose ();
      } wrimage.dispose ();

    }}//Save thumbnail Newimage.save (Savepath, System.Drawing.Imaging.ImageFormat.Jpeg);
    Releasing resources newg.dispose (); NewimaGe.
    Dispose ();
   Initimage.dispose (); } #endregion #region Other///<summary>///to determine whether the file type is a Web-formatted picture///(Note: jpg,gif,bmp,png)///</summa ry>///<param name= "ContentType" >HttpPostedFile.ContentType</param>///<returns></returns > public static bool Iswebimage (string contentType) {if ContentType = "Image/pjpeg | | contentType = =" image/ JPEG "| | ContentType = = "Image/gif" | | ContentType = = "Image/bmp" | |
   ContentType = = "Image/png") {return true;
   else {return false;
 }} #endregion}//end class}

The above is the entire content of this article, I hope to help you learn, but also hope that we support the cloud habitat community.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.