在Picturebox中调整大小并将图像保存为PNG

时间:2013-10-04 15:55:59

标签: .net vb.net image png picturebox

如何将100px调整为100px并将图像保存为图片框中的PNG?我可以保存,但输出文件将无法打开。我只有以下代码。

 picbox.Image.Save("example_file", System.Drawing.Imaging.ImageFormat.Png)

1 个答案:

答案 0 :(得分:2)

缩略图的基础知识非常简单:

  1. 创建所需大小的新位图
  2. 画原件;通过绘制到较小的BMP,它是缩略图
  3. 要保存,您可能需要在文件名中添加“.png”。由于您的图片位于picbox中,因此请将其打印出来以减少打字:

    Dim bmp As Bitmap = CType(picbox.Image, Bitmap)
    
    ' bmpt is the thumbnail
    Dim bmpt As New Bitmap(100, 100)
    Using g As Graphics = Graphics.FromImage(bmpt)
    
        ' draw the original image to the smaller thumb
        g.DrawImage(bmp, 0, 0,
                    bmpt.Width + 1,
                    bmpt.Height + 1)
    End Using
    
    bmpt.Save("example_file.PNG", System.Drawing.Imaging.ImageFormat.Png)
    

    注意:

    1. 完成后,您创建的Bitmap必须处理完毕。
      • 如果您需要进行保存,请添加bmpt.Dispose()作为最后一行。
      • 如果上述内容用作返回缩略图的方法,则获取新缩略图的代码必须将其丢弃。
    2. 如果原始图像已打开(如PictureBox中所示),则无法保存为相同的文件名。稍微更改名称,例如“myFoo”保存为“myFoo_t”。
    3. 上面的代码假定为方形图像。如果高度和宽度不同,则还需要缩放缩略图位图以防止缩略图失真。也就是说,从另一个计算新Bitmap的高度或宽度。