How to save an image instead of making a copy?

时间:2016-07-11 20:35:40

标签: vb.net jpeg bmp encoder system.drawing.imaging

I've been tasked with reducing the quality of pictures on a network drive's file/folder system.

Code:

    Dim bmp1 As New Bitmap("U:\Image1.jpg")
    Dim jpgEncoder As ImageCodecInfo = GetEncoder(ImageFormat.Jpeg)
    Dim myEncoder As System.Drawing.Imaging.Encoder = System.Drawing.Imaging.Encoder.Quality
    Dim myEncoderParameters As New EncoderParameters(1)

    Dim myEncoderParameter As New EncoderParameter(myEncoder, 50&)
    myEncoderParameters.Param(0) = myEncoderParameter
    bmp1.Save("U:\Image1.jpg", jpgEncoder, myEncoderParameters)

I get the following error: "A generic error occured in the GDI+". Is there anyway to save instead of copying to another file?

Thanks in advance!

1 个答案:

答案 0 :(得分:0)

The first line of your code locks the file until bmp1 is disposed. That's why you can't save to the original path.

Here's the way I use to load an image from file without actually locking the file:

    Dim bmp1 As Bitmap
    Using bmpTmp As New Bitmap("U:\Image1.jpg")
        bmp1 = New Bitmap(bmpTmp)
    End Using

Using this you'll be able to save directly to the original file path:

    '
    '
    bmp1.Save("U:\Image1.jpg", jpgEncoder, myEncoderParameters)
    bmp1.Dispose()

Hope that helps :)