How to get the bitmap/image from a Graphics object in C#?

前端 未结 7 1617
逝去的感伤
逝去的感伤 2021-02-20 07:34

I want to know what the intermediate state of the buffer where the Graphics object is drawing some stuff. How do I get hold of the bitmap or the image that it is drawing on?

7条回答
  •  萌比男神i
    2021-02-20 08:12

    This code working for me where I am converting image >> bitmap >> byte >> Base64 String.

    System.Drawing.Image originalImage = //your image
    
    //Create empty bitmap image of original size
    
    Bitmap tempBmp = new Bitmap(originalImage.Width, originalImage.Height);
    
    Graphics g = Graphics.FromImage(tempBmp);
    
    //draw the original image on tempBmp
    
    g.DrawImage(originalImage, 0, 0, originalImage.Width, originalImage.Height);
    
    //dispose originalImage and Graphics so the file is now free
    
    g.Dispose();
    
    originalImage.Dispose();
    
    using (MemoryStream ms = new MemoryStream())
    {
        // Convert Image to byte[]
        tempBmp.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
        //dpgraphic.image.Save(ms, System.Drawing.Imaging.ImageFormat.Bmp);
        byte[] imageBytes = ms.ToArray();
    
        // Convert byte[] to Base64 String
        string strImage = Convert.ToBase64String(imageBytes);
        sb.AppendFormat(strImage);
    }
    

提交回复
热议问题