Question

I'm using the following code (credit to Dolph Larson) to take a pre-made image file in bitmap format on an ASP.net server, draw a string on it and save it to file on the server. In the original code, he dumps the bitmap to the OutputStream, but I'd like to dump it instead to a file.

The version of code below successfully creates the new file, but when I open it, the string does not appear drawn on the image in the new file. I imagine I am missing a step -- when I use bitMapImage.Save("bitmaptest.jpg", ImageFormat.Jpeg) am I just re-saving the original instead of the modified version?

Here is the code:

        //Load the Image to be written on.
        Bitmap bitMapImage = new
        System.Drawing.Bitmap(Server.MapPath("generic.jpg"));
        Graphics graphicImage = Graphics.FromImage(bitMapImage);
        graphicImage.SmoothingMode = SmoothingMode.AntiAlias;
        graphicImage.DrawString("testing 1 2 3",
        new Font("Arial", 20, FontStyle.Bold),
        SystemBrushes.WindowText, new Point(0, 0));
        Response.ContentType = "image/jpeg";
        bitMapImage.Save("bitmaptest.jpg", ImageFormat.Jpeg);
        graphicImage.Dispose();
        bitMapImage.Dispose();

Thanks in advance!

Was it helpful?

Solution

Your code works just fine; You simply need to specify the path where you want to save the image:

Example:

//Load the Image to be written on.
        Bitmap bitMapImage = new
        System.Drawing.Bitmap((@"c:\\foo\\generic.jpg"));
        Graphics graphicImage = Graphics.FromImage(bitMapImage);
        graphicImage.DrawString("testing 1 2 3",
        new Font("Arial", 20, FontStyle.Bold),
        SystemBrushes.WindowText, new Point(0, 0)); 
        bitMapImage.Save("c:\\foo\\bitmaptest.jpg", ImageFormat.Jpeg);
        graphicImage.Dispose();
        bitMapImage.Dispose();

Note In your case, bitMapImage.Save needs to be as follows: bitMapImage.Save(Server.MapPath("~/Images")+"newImage.jpg",ImageFormat.Jpeg); since you are attempting to save the image on an asp.net app. ~/Images in my example is just the virtual directory Images inside your app.

OTHER TIPS

Yes ..You are saving the same image .You have to create a ne wbitmap and save it:-

Bitmap bitMapNew = Bitmap.FromHbitmap(graphicImage.GetHdc());
bitMapNew.Save("bitmaptest.jpg", System.Drawing.Imaging.ImageFormat.Jpeg);

Add these lines instead of your bitMapImage.save

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top