使用原始文件类型保存图像类型

时间:2015-01-22 00:36:10

标签: vb.net

我需要将图像保存到我的vb项目中。我正在使用一个进程使用它的文件名将图像保存到本地文件夹。但是,要做到这一点,我的代码必须将格式转换为.jpg。我需要的是用它的原始类型保存文件,因为我的项目将接收不同的图像类型和地图以及.pdf。有什么方法可以将imageformat.jpeg更改为其他可以将图像保存为原始格式的内容吗?

这是我用来保存图片的代码。 创建目录

 If (Not System.IO.Directory.Exists("d:/Site Images/" & Label33.Text & "/")) Then
                System.IO.Directory.CreateDirectory("d:/Site Images/" & Label33.Text & "/")
            End If

保存图片

Upload.PictureBox1.Image.Save("d:/Site Images/" & Label33.Text & "/" + Upload.TextBox1.Text, System.Drawing.Imaging.ImageFormat.Jpeg)

我正在使用MSVisual Studio 2013 Ultimate。

感谢

2 个答案:

答案 0 :(得分:1)

执行此操作的一种方法是,将图像加载到图片框中时,可以将原始扩展名保存在标记中:

Dim sFilename As String = "c:\test.png" ' However you are populating your picturebox, you can change this variable to the full path of the file

Upload.PictureBox1.Image = Image.FromFile(sFilename)
Upload.PictureBox1.Tag = System.IO.Path.GetExtension(sFilename).ToLower    ' Saves the extension to the picturebox in the tag field so that we can evaluate it later

然后,当您需要将图像保存回文件时,可以使用与以前相同的图像格式将其写回:

' Figure out what the original image format was

Dim oImageFormat As System.Drawing.Imaging.ImageFormat

Select Case PictureBox1.Tag.ToString
    Case ".jpeg", ".jpg"
        oImageFormat = System.Drawing.Imaging.ImageFormat.Jpeg
    Case ".png"
        oImageFormat = System.Drawing.Imaging.ImageFormat.Png
    Case ".bmp"
        oImageFormat = System.Drawing.Imaging.ImageFormat.Bmp
    Case ".gif"
        oImageFormat = System.Drawing.Imaging.ImageFormat.Gif
    Case ".tif", ".tiff"
        oImageFormat = System.Drawing.Imaging.ImageFormat.Tiff
    Case ".ico", ".icon"
        oImageFormat = System.Drawing.Imaging.ImageFormat.Icon
    Case ".emf"
        oImageFormat = System.Drawing.Imaging.ImageFormat.Emf
    Case ".exif"
        oImageFormat = System.Drawing.Imaging.ImageFormat.Exif
    Case ".wmf"
        oImageFormat = System.Drawing.Imaging.ImageFormat.Wmf
    Case Else
        ' This should never happen but just in case the extension cannot be found we default to jpeg output
        oImageFormat = System.Drawing.Imaging.ImageFormat.Jpeg
End Select

' Save the image with in the proper format again

Upload.PictureBox1.Image.Save("d:/Site Images/" & Label33.Text & "/" & Upload.TextBox1.Text & PictureBox1.Tag.ToString, oImageFormat)

有关pdf的说明: Picturebox控件不支持pdf文件,因此您无法以这种方式加载pdf。我建议你将pdf转换为支持的图像文件,然后在转换后将其加载到你的应用程序中。如果这不可行,您将不得不选择不同的控件来处理您的pdf,例如WebBrowser控件。

答案 1 :(得分:0)

您可以检查文件扩展名以查看原始图像文件格式。保存文件时,可以在Picturebox Image.Save函数中指定原始格式,例如System.Drawing.Imaging.ImageFormat.Png

如果.net不支持该格式(请参阅下面的链接),您可以使用第三方库,例如freeImage。

https://msdn.microsoft.com/en-us/library/system.drawing.imaging.imageformat%28v=vs.110%29.aspx