How to SHOW (JPEG) saved images from SQL Server (image type) ?

Hello,

I managed to save some processed JPEG files directly into the database (into an image field)
How can I get it back from the database and show it ?

Thanks, Yovav.
10X N C U L8R
Best Regards
YovavG@GMail.com
0
Yovav
3/24/2005 11:20:39 PM
asp.net.drawinggdi 1803 articles. 0 followers. Follow

4 Replies
994 Views

Similar Articles

[PageSpeed] 38
Get it on Google Play
Get it on Apple App Store

Response.ContentType = GetContentTypeFromDB();
Response.BinaryWrite(CreateThumbnail(GetDataFromDB(), width, height));


private byte[] CreateThumbnail(byte[] data, double width, double height)
{
System.Drawing.Image g = System.Drawing.Image.FromStream(new MemoryStream(Data));
Size ThumbSize = new Size();
ThumbSize = NewThumbSize(g.Width, g.Height, Width, Height);

Bitmap ImageOutput = new Bitmap(g, ThumbSize.Width, ThumbSize.Height);
MemoryStream ImageStream = new MemoryStream();
ImageOutput.Save(ImageStream, g.RawFormat);

byte[] BinaryData = new byte[ImageStream.Length];
ImageStream.Position = 0;
int n = ImageStream.Read(BinaryData, 0, BinaryData.Length);

g.Dispose();
ImageOutput.Dispose();

return BinaryData;
}

private Size NewThumbSize(double currentwidth, double currentheight, double newWidth, double newHeight)
{
double tempMultiplier;
if (currentheight > currentwidth) { tempMultiplier = newHeight / currentheight; }
else { tempMultiplier = newWidth / currentwidth; }

Size NewSize = new Size(System.Convert.ToInt32(currentwidth * tempMultiplier), System.Convert.ToInt32(currentheight * tempMultiplier));

return NewSize;
}


enjoy

0
mvdevnull
3/26/2005 9:39:09 PM

Thanks a lot Big Smile [:D] !

I also found more usefull stuff at: http://www.edneeis.com/%5Ctutorial.aspx?ID=7 :

Import/Export Images with a Database

With the new changes in ADO.NET I found that I had to go back and rewrite (go figure) some of my well used database code.  I searched the internet for a good example of how to write an image or file to a database and get back again, but couldn't find any I liked.  So I decided to write my own.  I'm sure other examples are out there, even if I didn't find them, but to save someone else a little bit of hassle I decided to post my version here.

 

Imports System.IO
Imports System.Data
Imports System.Data.SqlClient


Public Sub ImportImageToDB(ByVal dr As DataRow, ByVal Field As String, ByVal Img As Image)
'---------------------------------------------------------------------------------------
'Purpose : Writes an unknown file type to a database.
'Syntax : ImportImgagToDB(dr,"Picture",PictureBox1.Image)
'---------------------------------------------------------------------------------------
   Dim ms As MemoryStream = New MemoryStream()
   Img.Save(ms, Img.RawFormat)

   Dim data(ms.Length) As Byte
   ms.Position = 0
 
   ms.Read(data, 0, ms.Length)
   dr.Item(Field) = data
   ms.Close()
End Sub

Public Function ExportImageFromDB(ByVal dr As DataRow, ByVal Field As String) As Image
'---------------------------------------------------------------------------------------
' Purpose : Gets an Image from a database.
' Syntax : PictureBox1.Image=ExportImageFromDB(dr,"Picture")
'---------------------------------------------------------------------------------------
   Dim ms As MemoryStream = New MemoryStream()
   Dim data() As Byte
   Dim img As Image
   Try
      data = CType (dr.Item(Field), Byte())
      ms.Write(data, 0, data.GetUpperBound(0))
      img = Image.FromStream(ms)
   Catch ex As Exception
     'handle any errors other than no picture set in db yet
      If Not TypeOf ex Is ArgumentOutOfRangeException Then
         Throw ex
      End If
   Finally
      ms.Close()
      ms = Nothing
   End Try
 
   Return img
End Function

Public Function ExportImageFromDB(ByVal dr As SqlDataReader, ByVal Field As String) As Image
'---------------------------------------------------------------------------------------
' Author : Eddiem
' Purpose : Gets an Image from a database.
'---------------------------------------------------------------------------------------
   Dim  ms  As MemoryStream =NewMemoryStream()
   Dim data()As Byte
   Dim  img  As>  Image
   Try
      data =  CType(dr.Item(Field),Byte())
      ms.Write(data, 0, data.GetUpperBound(0))
      img = Image.FromStream(ms)
  Catch ex As Exception
      'handle any errors other than no picture set in db yet
      If Not TypeOf ex Is ArgumentOutOfRangeException Then
         Throw ex
     End If
  Finally
      ms.Close()
      ms = Nothing
   End Try
 
   Return img
End Function
 
 
Public Sub ImportFileToDB(ByVal dr As DataRow, ByVal Field As String, ByVal FilePath As String)
  '---------------------------------------------------------------------------------------
  ' Author : Eddiem
  ' Purpose : Writes an unknown file type to a database.
  '---------------------------------------------------------------------------------------
   Dim fs As FileStream = New FileStream(FilePath, FileMode.OpenOrCreate)
   Dim data(fs.Length) As  Byte
   fs.Position = 0
 
   fs.Read(data, 0, fs.Length)
   dr.Item(Field) = data
 
   fs.Close()
End  Sub
 
 
Public Sub ExportFileFromDB(ByVal dr As SqlDataReader, ByVal Field As String, ByVal FilePath As String)
  '---------------------------------------------------------------------------------------
  ' Author : Eddiem
  ' Purpose : Gets an unknown file type to a database.
  '---------------------------------------------------------------------------------------
   Dim fs As FileStream = New FileStream(FilePath, FileMode.OpenOrCreate)
   Dim data() AsByte
   Try
      data = CType(dr.Item(Field), Byte())
      fs.Write(data, 0, data.GetUpperBound(0))
   Catch ex As Exception
     'handle any errors other than no file in db
     If  Not  TypeOf ex Is ArgumentOutOfRangeException Then
         Throw ex
      EndIf
  Finally
      fs.Close()
      fs = Nothing
   End Try
End  Sub

Public Sub ExportFileFromDB(ByVal dr As DataRow, ByVal Field As String, ByVal FilePath As String)
  '---------------------------------------------------------------------------------------
  ' Author : Eddiem
  ' Purpose : Gets an unknown file type to a database.
  '---------------------------------------------------------------------------------------
   Dim fs As FileStream = New FileStream(FilePath, FileMode.OpenOrCreate)
   Dim data() As Byte
   Try
      data = CType>(dr.Item(Field), Byte())
      fs.Write(data, 0, data.GetUpperBound(0))
   Catch ex As Exception
     'handle any errors other than no file in db
      If Not> TypeOf ex Is ArgumentOutOfRangeException Then
         Throw ex
      End If
   Finally
      fs.Close()
      fs = Nothing
   End Try
End Sub


10X N C U L8R
Best Regards
YovavG@GMail.com
0
Yovav
3/27/2005 9:13:55 PM
Thanks for the code snippet, mvdevnull.  I've been trying to figure-out how to generate a thumbnail from a blob for quite some time and couldn't make it work... until now. Cool [H]

Here is
mvdevnull's code in VB.NET:

Private Function CreateThumbnail(ByVal data() As Byte, ByVal width As Double, ByVal height As Double) As Byte()

Dim g As System.Drawing.Image = System.Drawing.Image.FromStream(New MemoryStream(data))

Dim ThumbSize As New Size

ThumbSize = NewThumbSize(g.Width, g.Height, width, height)

Dim ImageOutput As New Bitmap(g, ThumbSize.Width, ThumbSize.Height)

Dim ImageStream As New MemoryStream

ImageOutput.Save(ImageStream, g.RawFormat)

Dim BinaryData(CInt(ImageStream.Length)) As Byte

ImageStream.Position = 0

Dim n As Integer = ImageStream.Read(BinaryData, 0, BinaryData.Length)

g.Dispose()

ImageOutput.Dispose()

Return BinaryData

End Function 'CreateThumbnail

Private Function NewThumbSize(ByVal currentwidth As Double, ByVal currentheight As Double, ByVal newWidth As Double, ByVal newHeight As Double) As Size

Dim tempMultiplier As Double

If currentheight > currentwidth Then

tempMultiplier = newHeight / currentheight

Else

tempMultiplier = newWidth / currentwidth

End If

Dim NewSize As New Size(System.Convert.ToInt32((currentwidth * tempMultiplier)), System.Convert.ToInt32((currentheight * tempMultiplier)))

Return NewSize

End Function 'NewThumbSize


Sincerely,
Todd M. Taylor
0
Blitzkrieg
6/7/2005 9:49:12 PM
Oh man, I hope this is what I have been looking for.  It looks like the image source may be set to read from stream.
Writing an image to a page via the Response.Write() method is "almost" useless to me.

The ASP.NET Cookbook has a nice code example for the thumbnail question, but son of a gun, no one explained to me how to retrieve an image from the database and view it besides binding the stream to a datalist "just" for images or a response object that obliterates html.

You could try this, too:
<code>

public byte[] FormatDbImage(Stream StreamObject, int IMAGE_SCALE, bool resizeByWidth)

{

if ( IMAGE_SCALE <= 0 )

{

AppendMessage(String.Format("<font color=\"Red\">No image scale has been specified.</font><br />"));

return null;

}

// create an image from the byte array

System.Drawing.Image originalImage = System.Drawing.Image.FromStream(StreamObject);

int newImageHeight;

int newImageWidth;

// Currently only gif and jpg images render well on all platforms

// Only allow these formats to be uploaded.

if(originalImage.RawFormat.Equals(ImageFormat.Gif) || originalImage.RawFormat.Equals(ImageFormat.Jpeg))

{

Bitmap ImageOutput = new Bitmap(originalImage);

if( resizeByWidth == true && IMAGE_SCALE < originalImage.Width )

{

newImageHeight =

Convert.ToInt32(Math.Round((Convert.ToDouble(IMAGE_SCALE) /

originalImage.Width) * originalImage.Height));

ImageOutput = new Bitmap(originalImage, IMAGE_SCALE, newImageHeight);

}

else if( IMAGE_SCALE < originalImage.Height )

{

newImageWidth =

Convert.ToInt32(Math.Round((Convert.ToDouble(IMAGE_SCALE) /

originalImage.Height) * originalImage.Width));

ImageOutput = new Bitmap(originalImage, newImageWidth, IMAGE_SCALE);

}

MemoryStream newStream = new MemoryStream();

ImageOutput.Save(newStream, originalImage.RawFormat);

byte[] ImageBinary = new byte[newStream.Length + 1];

newStream.Position = 0;

int n = newStream.Read(ImageBinary, 0, ImageBinary.Length);

originalImage.Dispose();

ImageOutput.Dispose();

return ImageBinary;

}

else

{

AppendMessage(String.Format("<font color=\"Red\">The image supplied was not the correct \"JPG\" or \"GIF\" format.</font>"));

return null;

}

}
</code>


If I am not learning patterns and practices, I am not harnessing the power of .NET
0
John
6/12/2005 2:57:26 AM
Reply:

Web resources about - How to SHOW (JPEG) saved images from SQL Server (image type) ? - asp.net.drawinggdi

Resources last updated: 12/1/2015 1:25:27 AM