Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to save a bitmap image as JPEG

Tags:

c#

image

jpeg

The problem is that the file is not saving as JPEG. Just a normal file.

This is my code so far:

private void btnSave_Click(object sender, EventArgs e)
{
    saveDialog.FileName = txtModelName.Text;

    if (saveDialog.ShowDialog() == DialogResult.OK)
    {
        Bitmap bmp = new Bitmap(pnlDraw.Width, pnlDraw.Height);

        pnlDraw.DrawToBitmap(bmp, new Rectangle(0, 0,
            pnlDraw.Width, pnlDraw.Height));

        bmp.Save(saveDialog.FileName, System.Drawing.Imaging.ImageFormat.Jpeg);
    }
}
like image 422
GameOver Avatar asked Jan 19 '14 14:01

GameOver


People also ask

Is bitmap available in JPEG format?

Other bitmap file formats For most purposes standardized compressed bitmap files such as GIF, PNG, TIFF, and JPEG are used; lossless compression in particular provides the same information as a bitmap in a smaller file size. TIFF and JPEG have various options. JPEG is usually lossy compression.

How do I save a photo as JPEG?

Go to File > Save as and open the Save as type drop-down menu. You can then select JPEG and PNG, as well as TIFF, GIF, HEIC, and multiple bitmap formats. Save the file to your computer and it will convert.


1 Answers

How about checking if file name has .jpg extension before saving it?

You can also change saveDialog to only allow user selecting .jpg images.

private void btnSave_Click(object sender, EventArgs e)
{
    saveDialog.FileName = txtModelName.Text;
    saveDialog.DefaultExt = "jpg";
    saveDialog.Filter = "JPG images (*.jpg)|*.jpg";    

    if (saveDialog.ShowDialog() == DialogResult.OK)
    {
        Bitmap bmp = new Bitmap(pnlDraw.Width, pnlDraw.Height);

        pnlDraw.DrawToBitmap(bmp, new Rectangle(0, 0,
            pnlDraw.Width, pnlDraw.Height));

        var fileName = saveDialog.FileName;
        if(!System.IO.Path.HasExtension(fileName) || System.IO.Path.GetExtension(fileName) != "jpg")
            fileName = fileName + ".jpg";

        bmp.Save(fileName, System.Drawing.Imaging.ImageFormat.Jpeg);
    }
}
like image 115
MarcinJuraszek Avatar answered Sep 21 '22 23:09

MarcinJuraszek