miércoles, 5 de mayo de 2010

Ajustar el tamaño fisico de una imgen para que encaje e un DIV

Esta funcion me la acaban de pasar, (me parece que se puede optimizar) por ese motivo no la voy a explicar , pero garantizarles que si funciona, solo usenla ,no reinventen la rueda


Dim ImagePercentSize As Integer = 100



Protected Function GetThumbNailSizeImage(ByVal binaryData() As Byte) As Byte()
Dim ThumbNailBinaryData() As Byte = Nothing
Try
Dim TempMemStream As New System.IO.MemoryStream(binaryData)
Dim ImageObj As System.Drawing.Image
Dim ThumbSizeImageObj As System.Drawing.Image
ImageObj = System.Drawing.Image.FromStream(TempMemStream)
Dim temHeight As Integer
Dim temWidth As Integer
temHeight = ImageObj.Height
temWidth = ImageObj.Width
Dim TempFileStream As New System.IO.MemoryStream
'If Imagesize is less than 20*20 then return the original image
If (temWidth <= 460 And temHeight <= 211) Then
Dim ImageBinaryData() As Byte
ImageObj.Save(TempFileStream, System.Drawing.Imaging.ImageFormat.Jpeg)

ImageBinaryData = New Byte(CType(TempFileStream.Length, Integer)) {}
ImageBinaryData = TempFileStream.ToArray()
Return ImageBinaryData
End If
Dim ImagePercentSize As Double = Me.ImagePercentSize


Dim a, b As Double

If (460 > temWidth) And 211 > temHeight Then
a = 211 / temHeight
b = 460 / temWidth

If (a < b) Then
temHeight = CInt(temHeight * a)
temWidth = CInt(temWidth * a)
Else
temHeight = CInt(temHeight * b)
temWidth = CInt(temWidth * b)
End If

Else
a = 211 / temHeight
b = 460 / temWidth

If (a < b) Then
temHeight = CInt(temHeight * a)
temWidth = CInt(temWidth * a)
Else
temHeight = CInt(temHeight * b)
temWidth = CInt(temWidth * b)
End If

End If



'Create thumbnail size of the original Image ImageObj
If (Me.ImagePercentSize = 0.0) Then
ThumbSizeImageObj = ImageObj.GetThumbnailImage(temWidth, temHeight, Nothing, IntPtr.Zero)
Else
ThumbSizeImageObj = ImageObj.GetThumbnailImage(temWidth, temHeight, Nothing, IntPtr.Zero)
End If
ThumbSizeImageObj.Save(TempFileStream, System.Drawing.Imaging.ImageFormat.Jpeg)

ThumbNailBinaryData = New Byte(CType(TempFileStream.Length, Integer)) {}
ThumbNailBinaryData = TempFileStream.ToArray()
Catch ex As Exception

End Try
Return ThumbNailBinaryData
End Function


'----------- para llamar a la funcion
Dim binaryData() As Byte = f.Item(0) ' donde f.Item(0) es un conuto de Byte tra

Dim TempMemStream As New System.IO.MemoryStream(GetThumbNailSizeImage(binaryData))

'luego esta imagen redimencionada la puden guardar de la siguiente manera

Dim image_ As New Bitmap(TempMemStream)
Dim filepath As String = Server.MapPath("images/")
Dim dir As New DirectoryInfo(filepath)
Dim filecount As FileInfo() = dir.GetFiles()
Dim i As Integer = filecount.Length
Dim imagename As String = filepath + ((i + 1) & ".jpg")
image_.Save(imagename)

Nota.- cuando agregen la imagen al componente html , no usen las propiedades width ni heigth

No hay comentarios:

Publicar un comentario