【发布时间】:2016-05-08 15:46:18
【问题描述】:
我收到错误A Graphics object cannot be created from an image that has an indexed pixel format.
下面的代码在我的服务器上保存图像
imageURL="http://www.wijny.nl/imagestore/product/375/villamariaestateprivatebinsauvignonblancmarlboroughnewzealand10126029.jpg"
代码不保存任何图像时
imageURL="http://www.wijny.nl/imagestore/product/377/villamariasinglevineyardcha.gif"
我看到的唯一区别是图像源的格式,.jpg 文件存储正确,.gif 文件不正确。如何确保代码保存任何类型的图像,无论是 .png、.jpg 还是 .gif?
Dim imgRequest As WebRequest
Dim imgResponse As WebResponse
Dim imgStream As Stream
imgRequest = WebRequest.Create(imageURL)
Dim localImageFilename as String = 'test.jpg'
Try
imgResponse = imgRequest.GetResponse()
imgStream = imgResponse.GetResponseStream()
Catch ex As Exception
LogError("imgRequest.GetResponse", ex.Message)
End Try
imgRemoteImage = System.Drawing.Image.FromStream(imgStream)
localImagePath = Server.MapPath(ConfigurationManager.AppSettings("photospath").ToString) + localImageFilename
ResizeAndSaveImage(1200, 1200, localImagePath, imgRemoteImage)
Private Function ResizeAndSaveImage(ByVal maxWidth As Integer, ByVal maxHeight As Integer, ByVal path As String, ByVal img As System.Drawing.Image) As Boolean
Dim newWidth, newHeight As Integer
Dim scaleFactor As Double
Dim bResult As Boolean
newWidth = img.Width
newHeight = img.Height
If img.Width > maxWidth Or img.Height > maxHeight Then
If img.Width > maxWidth Then
scaleFactor = maxWidth / img.Width
newWidth = Math.Round(img.Width * scaleFactor, 0)
newHeight = Math.Round(img.Height * scaleFactor, 0)
End If
If newHeight > maxHeight Then
scaleFactor = maxHeight / newHeight
newWidth = Math.Round(newWidth * scaleFactor, 0)
newHeight = Math.Round(newHeight * scaleFactor, 0)
End If
End If
Try
Dim bMap As New Bitmap(newWidth, newHeight, img.PixelFormat)
Dim gr As System.Drawing.Graphics = System.Drawing.Graphics.FromImage(bMap)
gr.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality
gr.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality
gr.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High
Dim rectDestination As New System.Drawing.Rectangle(0, 0, newWidth, newHeight)
gr.DrawImage(img, rectDestination, 0, 0, img.Width, img.Height, GraphicsUnit.Pixel)
bMap.Save(path, System.Drawing.Imaging.ImageFormat.Jpeg)
bMap.Dispose()
bResult = True
Catch ex As Exception
End Try
Return bResult
End Function
【问题讨论】:
标签: asp.net vb.net stream jpeg gif