I'm resizing images on my own server that come from a remote server. This works perfectly, but for some images it resizes it completely wrong.
This image works perfectly: http://www.topwedding.com/bigimage/Wedding%20Dresses/HSTSKN510/Strapless-Mermaid-Appliqued-Wedding-Dress-with-Ruched-Bodice-and-Pick-Up-Skirt.jpg
But for example this image, works terribly and ends up being really small: http://www.topwedding.com/bigimage/Wedding%20Dresses/HS01116007/Floral-One-Shoulder-Organza-over-Satin-A-Line-Bridal-Gown-with-Pick-Ups.jpg
Upon inspection it turns out the first image has a 72 Pixels/inch and the second image has 951 Pixels/Inch.
Bad resizing was the same issue I had before (see here)
But I thought that was now solved by using the PixelWidth
and PixelHeight
properties in my code, as suggested in the other post.
The goal is to have thumbnails that are 200 pixels wide that can be shown on a product overview page. How can I make sure the images end up being the same size?
The full code is below:
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
ResizeAndSaveFast(200, 200, "http://www.topwedding.com/bigimage/Wedding%20Dresses/HSTSKN510/Strapless-Mermaid-Appliqued-Wedding-Dress-with-Ruched-Bodice-and-Pick-Up-Skirt.jpg", Server.MapPath("images\") + "1.png")
ResizeAndSaveFast(200, 200, "http://www.topwedding.com/bigimage/Wedding%20Dresses/HS01116007/Floral-One-Shoulder-Organza-over-Satin-A-Line-Bridal-Gown-with-Pick-Ups.jpg", Server.MapPath("images\") + "2.png")
End Sub
Private Function ResizeAndSaveFast(ByVal maxWidth As Integer, ByVal maxHeight As Integer, ByVal imageURL As String, ByVal saveToPath As String) As Boolean
Dim imgRequest As WebRequest = WebRequest.Create(imageURL)
Dim imgResponse As WebResponse
imgResponse = imgRequest.GetResponse()
Dim streamPhoto As Stream = imgResponse.GetResponseStream()
Dim memStream As New MemoryStream
streamPhoto.CopyTo(memStream)
memStream.Position = 0
Dim bfPhoto As BitmapFrame = ReadBitmapFrame(memStream)
Dim newWidth, newHeight As Integer
Dim scaleFactor As Double
newWidth = bfPhoto.PixelWidth
newHeight = bfPhoto.PixelHeight
If bfPhoto.PixelWidth > maxWidth Or bfPhoto.PixelHeight > maxHeight Then
If bfPhoto.PixelWidth > maxWidth Then
scaleFactor = maxWidth / bfPhoto.PixelWidth
newWidth = Math.Round(bfPhoto.Width * scaleFactor, 0)
newHeight = Math.Round(bfPhoto.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
Dim bfResize As BitmapFrame = FastResize(bfPhoto, newWidth, newHeight)
If bfResize Is Nothing Then Return False
Dim baResize As Byte() = ToByteArray(bfResize)
File.WriteAllBytes(saveToPath, baResize)
Return True
End Function