Search code examples
asp.netvb.netcontent-typesystem.drawing

Display resized image as a return value and not as page content


On Page_Load, I want the page to display an image the same way it displays when you "Open image in a new tab". In other words, I want the page to display as content type Image/jpeg instead of rendering the image in img HTML tag.

I successfully displayed an image this way using the below code on Page_Load:

Page.Response.ContentType="image/jpeg"
Page.Response.WriteFile("Path_to_the_Image")

However, my case requires displaying the image after being resized. I created a function that resizes the image and returns the resized image as Drawing.Bitmap

ResizeImage(bmSource As Drawing.Bitmap, TargetWidth As Int32, TargetHeight As Int32)

How can I use the returned value of that function and display it the same way I displayed the first image?

Page.Response.WriteFile() requires a String as an input. Is there a way where I can display the image of type Image or System.Bitmap directly into the page without having to save it in a temp folder and then use its path (As a String) and pass it to Page.Response.WriteFile?


Solution

  • Page.Response.ContentType="image/jpeg"
    Using resizedImage As Bitmap = ResizeImage(source, 100, 100)
        source.Dispose()    
        resizedImage.Save(Page.Response.OutputStream, System.Drawing.Imaging.ImageFormat.Jpeg)
    End Using
    Page.Response.Flush()
    

    That should work, maybe there's some error in my syntax. I do not often code in vb.net so.

    Edited the code because of @Joel Coehoorn note