简体   繁体   English

如何将位图图像保存为 JPEG

[英]How to save a bitmap image as JPEG

The problem is that the file is not saving as JPEG.问题是文件没有保存为 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);
    }
}

How about checking if file name has .jpg extension before saving it?如何在保存之前检查文件名是否具有.jpg扩展名?

You can also change saveDialog to only allow user selecting .jpg images.您还可以将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);
    }
}
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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM