views:

50

answers:

3

I need to take an uploaded image, resize it, and save it to the database. Simple enough, except I don't have access to save any temp files to the server. I'm taking the image, resizing it as a Bitmap, and need to save it to a database field as the original image type (JPG for example). How can I get the FileBytes() like this, so I can save it to the database?

Before I was using ImageUpload.FileBytes() but now that I'm resizing I'm dealing with Images and Bitmaps instead of FileUploads and can't seem find anything that will give me the bytes.

Thanks!

+1  A: 

This is what I've done to resize images.

    private byte[] toBytes(Image image)
    {            
        Bitmap resized = new Bitmap(image, yourWidth, yourHeight);            
        System.IO.MemoryStream ms = new System.IO.MemoryStream();            
        resized.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
        resized.Dispose();
        return ms.ToArray();            
    }
Aaron
+1  A: 

See http://stackoverflow.com/questions/87753/resizing-an-image-without-losing-any-quality You can then write your image (Bitmap.SaveToStream) to a MemoryStream and call ToArray to get the bytes.

John JJ Curtis
A: 

Just pass FileUpload1.PostedFile.InputStream and the full path of where to save the image to the following subroutine...

Public Sub ResizeAndSaveImage(ByRef SourceImageStream As Stream, _
                              ByVal strSavePath As String, _
                              ByVal intPreferredWidth As Integer)
    Dim bmpSource As New Bitmap(SourceImageStream)

    If bmpSource.Width > intPreferredWidth Then
        Dim decAspectRatio As Decimal = bmpSource.Width / bmpSource.Height
        Dim intNewHeight As Integer = intPreferredWidth / decAspectRatio
        Dim bmpResized As New Bitmap(intPreferredWidth, intNewHeight)
        Dim graResized As Graphics = Graphics.FromImage(bmpResized)

        graResized.DrawImage(bmpSource, 0, 0, bmpResized.Width, bmpResized.Height)
        bmpResized.Save(strSavePath, ImageFormat.Jpeg)
    Else
        bmpSource.Save(strSavePath, ImageFormat.Jpeg)
    End If
End Sub
Josh Stodola