Get bitmap and draw it into image

一笑奈何 提交于 2019-12-13 19:03:12

问题


I am trying to save my drawing from picturebox into bitmap and draw that bitmap into image. So far, nothing has appeared in the final image, but while debugging I can only say, that the original bitmap is not null and with/height are correct. However nothing appears after I draw it into image.

I save my drawing into bitmap like this:

GraphicsPath path = RoundedRectangle.Create(x, y, width, height, corners, RoundedRectangle.RectangleCorners.All);
        g.FillPath(Brushes.LightGray, path);


        g.SetClip(path);

        using (Font f = new Font("Tahoma", 9, FontStyle.Bold))
            g.DrawString(mtb_hotspotData.Text, f, Brushes.Black, textX, textY);
        g.ResetClip();

        bitmap = new Bitmap(width, height, g);

Then save it:

hs.bitmap = new Bitmap(bitmap);

And finally use it:

for (int i = 0; i < imageSequence.Count; i++) {
            Graphics g = Graphics.FromImage(imageSequence[i]);
            //g.CompositingMode = CompositingMode.SourceOver;
            //hotspot.bitmap.MakeTransparent();
            int x = hotspot.coordinates[i].X;
            int y = hotspot.coordinates[i].Y;
            g.DrawImage(hotspot.bitmap, new Point(x, y));
        }


        return imageSequence;

So far I was not able to find any problem in this solution, therefore I have no idea, where the malfunction is.


回答1:


You seem to misunderstand the relation of a Bitmap and a Graphics object.

  • A Graphics object does not contain any graphics; it is a tool used to draw into a bitmap of some sort.

  • The Bitmap constructor you are using (public Bitmap(int width, int height, Graphics g)) does not really connect the Bitmap and the Graphics object. It only uses the dpi resolution from the Graphics.

You don't show how your Graphics is created. If you want to draw into a Bitmap (as opposed to a control's surface) the most direct way is this:

Bitmap bitmap = new Bitmap(width, height);
bitmap.SetResolution(dpiX, dpiY);  // optional

using (Graphics G = Graphics.FromImage(bitmap ))
{

   // do the drawing..
   // insert all your drawing code here!

}

// now the Bitmap can be saved or cloned..
bitmap.Save(..);
hs.bitmap = new Bitmap(bitmap);  // one way..
hs.bitmap = bitmap.Clone();      // ..or the other

// and finally disposed of (!!)
bitmap.Dispose();


来源:https://stackoverflow.com/questions/29576806/get-bitmap-and-draw-it-into-image

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!