473,396 Members | 2,111 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,396 software developers and data experts.

Image resize on the fly

229 100+
Hi, I have this asp.net code to resize my images. It works fine although it resizes images without keeping the aspect ratio. My image display page is an .asp page extension.

I would rather keep aspect ratio of my images. Could anyone tell me if there is a tinker one could do with this code to do that or would i need to look for another code to do the job.

Thanks in advance

Richard

Expand|Select|Wrap|Line Numbers
  1. <%@ OutputCache Duration="600" VaryByParam="*" %>
  2. <%@ Page Debug="false" %>
  3. <%@ Import Namespace="System.Drawing" %>
  4. <%@ Import Namespace="System.Drawing.Imaging" %>
  5. <%@ Import Namespace="System.IO" %>
  6. <script language="VB" runat="server">
  7.  
  8.     Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)
  9.  
  10.         On Error Resume Next        
  11.  
  12.         'retrieve relative path to image
  13.         Dim imageUrl As String = HttpUtility.UrlDecode(Request.QueryString("img"))    
  14.         dim doresize As Boolean
  15.         doresize=true       
  16.  
  17.         response.contenttype="image/jpeg"
  18.  
  19.         Dim pictureResizeSecCode As String = "quickresize" 'change this code!
  20.         Dim resizePictureToPx As String = HttpUtility.UrlDecode(Request.QueryString("resizePictureToPx"))
  21.  
  22.         'prepare thumbnail
  23.         Dim fullSizeImg As System.Drawing.Image
  24.         fullSizeImg = System.Drawing.Image.FromFile(Server.MapPath(imageUrl))        
  25.  
  26.         If Request.QueryString("getWidthOnly") = "true" Then
  27.             Response.Write(fullSizeImg.Width)
  28.             fullSizeImg.Dispose()
  29.             Response.End()
  30.         End If
  31.  
  32.         If fullSizeImg Is Nothing Then Response.End()            
  33.  
  34.         '??
  35.         Dim dummyCallBack As System.Drawing.Image.GetThumbnailImageAbort
  36.         dummyCallBack = New System.Drawing.Image.GetThumbnailImageAbort(AddressOf ThumbnailCallback)
  37.  
  38.         Dim thumbNailImg As System.Drawing.Image
  39.         Dim newWidth As Integer
  40.         Dim newHeight As Integer
  41.         Dim maxSize As Integer
  42.         If IsNumeric(Request.QueryString("maxSize")) And Request.QueryString("maxSize") <> "" Then
  43.             maxSize = Request.QueryString("maxSize")
  44.         Else
  45.             maxSize = 0
  46.         End If    
  47.  
  48.         'calculate new widht/height, if any  
  49.  
  50.         If fullSizeImg.Width > maxSize Or fullSizeImg.Height > maxSize Then            
  51.  
  52.             'for better quality
  53.             fullSizeImg.RotateFlip(System.Drawing.RotateFlipType.Rotate90FlipX)
  54.             fullSizeImg.RotateFlip(System.Drawing.RotateFlipType.Rotate90FlipX)
  55.  
  56.             If fullSizeImg.Width >= fullSizeImg.Height Then
  57.                 newWidth = maxSize
  58.                 newHeight = (fullSizeImg.Height / fullSizeImg.Width) * maxSize
  59.             Else
  60.                 newWidth = (fullSizeImg.Width / fullSizeImg.Height) * maxSize
  61.                 newHeight = maxSize
  62.             End If
  63.         Else
  64.  
  65.             newWidth = fullSizeImg.Width
  66.             newHeight = fullSizeImg.Height
  67.             doresize = False
  68.  
  69.         End If
  70.  
  71.         dim FSR as string = Request.QueryString("FSR")
  72.         IF FSR IS NOTHING ANDALSO FSR.length = 0 Then
  73.         FSR="0"
  74.         END IF
  75.  
  76.         If FSR = "1" Then
  77.             If newWidth < newHeight Then
  78.                 thumbNailImg = fullSizeImg.GetThumbnailImage(newWidth * (newHeight / newWidth), newHeight * (newHeight / newWidth), dummyCallBack, IntPtr.Zero)
  79.                 thumbNailImg = CropImage(thumbNailImg, New Point(0, (newHeight - newWidth) / 2), New Point(newHeight, newHeight + (newHeight - newWidth) / 2))
  80.             Else
  81.                 thumbNailImg = fullSizeImg.GetThumbnailImage(newWidth * (newWidth / newHeight), newHeight * (newWidth / newHeight), dummyCallBack, IntPtr.Zero)
  82.                 thumbNailImg = CropImage(thumbNailImg, New Point((newWidth - newHeight) / 2, 0), New Point(newWidth + ((newWidth - newHeight) / 2), newWidth))
  83.         End If                
  84.         Else
  85.             If doresize=True Then
  86.                 thumbNailImg = fullSizeImg.GetThumbnailImage(newWidth, newHeight, dummyCallBack, IntPtr.Zero)
  87.             else                
  88.                 thumbNailImg = fullSizeImg                    
  89.             End If
  90.         End If
  91.  
  92.  
  93.         createOutput(thumbNailImg)                   
  94.  
  95.  
  96.         'Clean up / Dispose...
  97.         thumbNailImg.Dispose()
  98.  
  99.         'Clean up / Dispose...
  100.         fullSizeImg.Dispose()
  101.  
  102.         On Error GoTo 0
  103.     End Sub
  104.  
  105.     Sub createOutput(ByRef ImageObj As System.Drawing.Image)
  106.  
  107.         On Error Resume Next
  108.  
  109.         Dim specialEffect as String = HttpUtility.UrlDecode(Request.QueryString("SE"))
  110.  
  111.         select case specialEffect
  112.             case "1"
  113.                 PureBW (ImageObj)
  114.             case "2"
  115.                 GrayScale (ImageObj)
  116.             case "3"
  117.                 PixelLoopConvert (ImageObj)
  118.  
  119.         end select
  120.  
  121.         ImageObj.Save(Response.OutputStream, ImageFormat.Jpeg)
  122.  
  123.         On Error GoTo 0
  124.  
  125.     End Sub
  126.  
  127.     Private Function CropImage(ByVal OriginalImage As Bitmap, ByVal TopLeft As Point, ByVal BottomRight As Point) As Bitmap
  128.         Dim btmCropped As New Bitmap((BottomRight.Y - TopLeft.Y), (BottomRight.X - TopLeft.X))
  129.         Dim grpOriginal As Graphics = Graphics.FromImage(btmCropped)
  130.  
  131.         grpOriginal.DrawImage(OriginalImage, New Rectangle(0, 0, btmCropped.Width, btmCropped.Height), _
  132.             TopLeft.X, TopLeft.Y, btmCropped.Width, btmCropped.Height, GraphicsUnit.Pixel)
  133.         grpOriginal.Dispose()
  134.  
  135.         Return btmCropped
  136.     End Function
  137.  
  138.  
  139.     Function ThumbnailCallback() As Boolean
  140.  
  141.         Return False
  142.  
  143.     End Function
  144.  
  145.     Public Function PureBW(ByVal image As System.Drawing.Bitmap, Optional ByVal Mode As BWMode = BWMode.By_Lightness, Optional ByVal tolerance As Single = 0) As System.Drawing.Bitmap
  146.         Dim x As Integer
  147.         Dim y As Integer
  148.         If tolerance > 1 Or tolerance < -1 Then
  149.             Throw New ArgumentOutOfRangeException
  150.             Exit Function
  151.         End If
  152.         For x = 0 To image.Width - 1 Step 1
  153.             For y = 0 To image.Height - 1 Step 1
  154.                 Dim clr As Color = image.GetPixel(x, y)
  155.                 If Mode = BWMode.By_RGB_Value Then
  156.                     If (CInt(clr.R) + CInt(clr.G) + CInt(clr.B)) > 383 - (tolerance * 383) Then
  157.                         image.SetPixel(x, y, Color.White)
  158.                     Else
  159.                         image.SetPixel(x, y, Color.Black)
  160.                     End If
  161.                 Else
  162.                     If clr.GetBrightness > 0.5 - (tolerance / 2) Then
  163.                         image.SetPixel(x, y, Color.White)
  164.                     Else
  165.                         image.SetPixel(x, y, Color.Black)
  166.                     End If
  167.                 End If
  168.             Next
  169.         Next
  170.         Return image
  171.     End Function
  172.  
  173.     Enum BWMode
  174.         By_Lightness
  175.         By_RGB_Value
  176.     End Enum
  177.  
  178.     Public Function GrayScale (ByVal image As System.Drawing.Bitmap)
  179.  
  180.         Dim X As Integer
  181.         Dim Y As Integer
  182.         Dim clr As Integer
  183.  
  184.         For X = 0 To image.Width - 1
  185.             For Y = 0 To image.Height - 1
  186.                 clr = (CInt(image.GetPixel(X, Y).R) + _
  187.                        image.GetPixel(X, Y).G + _
  188.                        image.GetPixel(X, Y).B) \ 3
  189.                 image.SetPixel(X, Y, Color.FromArgb(clr, clr, clr))
  190.             Next Y
  191.         Next X
  192.  
  193.         return image
  194.  
  195.     End Function
  196.  
  197.     Public Function PixelLoopConvert (ByVal Image As System.Drawing.Bitmap)    
  198.  
  199.     For i As Integer = 0 To Image.Width - 1
  200.       For j As Integer = 0 To Image.Height - 1
  201.         Dim iRed As Integer = Image.GetPixel(i, j).R
  202.         Dim iGreen As Integer = Image.GetPixel(i, j).G
  203.         Dim iBlue As Integer = Image.GetPixel(i, j).B
  204.  
  205.         ' Bereken de nieuwe RGB-waarde voor deze pixel:
  206.         Dim iSepiaRed As Integer = Math.Min(Convert.ToInt32(iRed * 0.393 + iGreen * 0.769 + iBlue * 0.189), 255)
  207.         Dim iSepiaGreen As Integer = Math.Min(Convert.ToInt32(iRed * 0.349 + iGreen * 0.686 + iBlue * 0.168), 255)
  208.         Dim iSepiaBlue As Integer = Math.Min(Convert.ToInt32(iRed * 0.272 + iGreen * 0.534 + iBlue * 0.131), 255)
  209.  
  210.         ' Wijzig de RGB-waarde van de huidige pixel van de oude naar de nieuwe:
  211.         Image.SetPixel(i, j, Color.FromArgb(iSepiaRed, iSepiaGreen, iSepiaBlue))
  212.       Next
  213.     Next
  214.  
  215.     Return Image
  216.  
  217.   End Function
  218.  
  219. </script>
  220.  
  221.  

Expand|Select|Wrap|Line Numbers
  1. <img src="showthumb.aspx?fsr=1&amp;maxsize=200&amp;img=<%=Server.URLPathEncode(CStr(thumbnail))%>"/>
Dec 9 '14 #1
1 1626
Frinavale
9,735 Expert Mod 8TB
The way I keep the aspect ratio of my thumbnail images is to reduce the original height and width at the same rate until they both fit within the boundaries of my size restrictions.

Something like:

Expand|Select|Wrap|Line Numbers
  1. Dim newHeight As Integer = fullSizeImg.Height
  2. Dim newWidth As Integer = fullSizeImg.Width
  3. If  newHeight > maxSize Or  newWidth > maxSize Then
  4.   While newHeight > maxSize Or newWidth > smallWidth
  5.     newHeight = newHeight - (newHeight * 0.05)
  6.     newWidth = newWidth - (newWidth * 0.05)
  7.   End While
  8. End If
-Frinny
Dec 9 '14 #2

Sign in to post your reply or Sign up for a free account.

Similar topics

3
by: Paul Jaeger | last post by:
I have jpeg images that are 2848 x 4256 pixels. I want to programatically convert them to images that are approximately 427 x 638 (that maintains the ratio) and save to new jpeg files. How can...
0
by: Jay | last post by:
Hi guys, trying to fix a problem with an image resize routine. The code posted below uploads and resizes a jpeg, probablem is, the outlook can look a bit bitty becuase of teh samller size...is...
4
by: vunet.us | last post by:
Hello, What is the best image resizing tool is out there? I want to resize images in ASP page when users upload them into some directory. Your recommendations are super welcome. Thank you.
12
by: Shawn Northrop | last post by:
Ive been searching for an image resize tutorial for a while now and found this code which worked nicely. I was unable to find the full source code but i think i pieced together the code from the...
2
by: Tim Arnold | last post by:
Hi, I'm using the Image module to resize PNG images from 300 to 100dpi for use in HTML pages, but I'm losing some vertical and horizontal lines in the images (usually images of x-y plots). ...
2
by: Dominic Vella | last post by:
Hi, I know I seem to have the really complicated questions, but I guess that's why I'm here. This is a little verbose, only because I've been trying to crack this for a week now. Your help...
8
by: infoseekar | last post by:
Image Resize & Rotation Hi I have 2 scripts, one for Image rotation and other image resize and they both are working. Image resize scripts load the picture and resize it and Image rotation...
2
by: Noorain | last post by:
Hi, another problem. i upload width=800 pixels image in database through. this image resize by thumb image & bis image. thumb image width is 100 pixel & big image width is 400 pixel. 800 pixel image...
22
by: simon2x1 | last post by:
i have an image which width is 213 and height is 200 when i echo the image and i resize it echo "<img src='company/$present' width='70' height='68'/>"; the image was not as clear as when it was...
1
by: fraser5002 | last post by:
Hi I have a problem with the code im using to resize an image to fit it within a fixed size cell in a table. The code is supposed to resize the image and retain its aspect ratio. But it does not...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.