如何将位图图像保存为JPEG

时间:2014-01-19 14:30:38

标签: c#

问题是该文件未保存为JPEG。只是一个普通的文件。

到目前为止,这是我的代码:

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);
    }
}

2 个答案:

答案 0 :(得分:10)

在保存之前检查文件名是否有.jpg扩展名怎么样?

您还可以将saveDialog更改为仅允许用户选择.jpg图片。

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);
    }
}

答案 1 :(得分:0)

int width;
int height;
int stride;
int x;
int y;
string filename;

Bitmap bitmap = new Bitmap(width,height,stride,PixelFormat.Format32bppArgb,new IntPtr());

//then set the pixel;
bitmap.SetPixel(x,y,Colors.Black);
bitmap.Save(filename);