Graphics object to image file

前端 未结 3 2025
说谎
说谎 2020-12-06 11:56

I would like to crop and resize my image. Here is my code:

Image image = Image.FromFile(AppDomain.CurrentDomain.BaseDirectory + \"Cropper/tests/castle.jpg\")         


        
3条回答
  •  春和景丽
    2020-12-06 12:11

    No, the Graphics object doesn't contain any image data, it's used to draw on a canvas, which usually is the screen or a Bitmap object.

    So, you need to create a Bitmap object with the correct size to draw on, and create the Graphics object for that bitmap. Then you can save it. Remember that object implementing IDisposable should be disposed, for example using the using clause:

    using (Image image = Image.FromFile(AppDomain.CurrentDomain.BaseDirectory + "Cropper/tests/castle.jpg")) {
    
       // Create bitmap
       using (Bitmap newImage = new Bitmap(200, 120)) {
    
          // Crop and resize the image.
          Rectangle destination = new Rectangle(0, 0, 200, 120);
          using (Graphics graphic = Graphics.FromImage(newImage)) {
             graphic.DrawImage(image, destination, int.Parse(X1.Value), int.Parse(Y1.Value), int.Parse(Width.Value), int.Parse(Height.Value), GraphicsUnit.Pixel);
          }
          newImage.Save(AppDomain.CurrentDomain.BaseDirectory + "Cropper/tests/castle_icon.jpg", ImageFormat.Jpeg);
       }
    }
    

提交回复
热议问题