i have the below code, i am looking to crop and resize at the same time, i use the below function, i am looking to have 150 x 150 px image size cropped centered, but the below function always if the image width > height, the output image will be 200x150, but i need it to be 150x150 px,, any help
Function SavetoDisk(FU As FileUpload, ByVal para_Save_to_Path As String, ByVal maxHeight As Integer, ByVal maxWidth As Integer, para_FileExt As String, anchor As AnchorPosition)
Using image As Image = image.FromStream(FU.PostedFile.InputStream)
Dim sourceWidth As Integer = image.Width
Dim sourceHeight As Integer = image.Height
Dim sourceX As Integer = 0
Dim sourceY As Integer = 0
Dim destX As Integer = 0
Dim destY As Integer = 0
Dim nPercent As Decimal = 0
Dim nPercentW As Decimal = 0
Dim nPercentH As Decimal = 0
nPercentW = (Convert.ToSingle(maxWidth) / Convert.ToSingle(sourceWidth))
nPercentH = (Convert.ToSingle(maxHeight) / Convert.ToSingle(sourceHeight))
If (nPercentH < nPercentW) Then
nPercent = nPercentW
Select Case (anchor)
Case AnchorPosition.Top
destY = 0
Case AnchorPosition.Bottom
destY = Convert.ToInt32(maxHeight - (sourceHeight * nPercent))
Case Else
destY = Convert.ToInt32((maxHeight - (sourceHeight * nPercent)) / 2)
End Select
Else
nPercent = nPercentH
Select Case (anchor)
Case AnchorPosition.Left
destX = 0
Case AnchorPosition.Right
destX = Convert.ToInt32((maxWidth - (sourceWidth * nPercent)))
Case Else
destX = Convert.ToInt32(((maxWidth - (sourceWidth * nPercent)) / 2))
End Select
End If
Dim destWidth As Integer = Convert.ToInt32((sourceWidth * nPercent))
Dim destHeight As Integer = Convert.ToInt32((sourceHeight * nPercent))
Using thumbnailBitmap As Bitmap = New Bitmap(destWidth, destHeight)
Using thumbnailGraph As Graphics = Graphics.FromImage(thumbnailBitmap)
thumbnailGraph.CompositingQuality = CompositingQuality.HighQuality
thumbnailGraph.SmoothingMode = SmoothingMode.HighQuality
thumbnailGraph.InterpolationMode = InterpolationMode.HighQualityBicubic
Dim imageRectangle As Rectangle = New Rectangle(0, 0, destHeight, destHeight)
thumbnailGraph.DrawImage(image, New Rectangle(destX, destY, destWidth, destHeight), New Rectangle(sourceX, sourceY, sourceWidth, sourceHeight), GraphicsUnit.Pixel)
Dim jpegCodec As ImageCodecInfo = Findcodecinfo("JPEG")
If Not IsNothing(jpegCodec) Then
Dim encoderParameters As EncoderParameters = New EncoderParameters(1)
encoderParameters.Param(0) = New EncoderParameter(Encoder.Quality, 80)
thumbnailBitmap.Save(para_Save_to_Path, jpegCodec, encoderParameters)
Else
thumbnailBitmap.Save(para_Save_to_Path, ImageFormat.Jpeg)
End If
End Using
End Using
End Using
End Function
Steps to achieve what you want:
Figure out ratio of height to width
Scale the larger dimension down to 150px and the smaller dimension down to ratio * 150px.
Draw the result in the middle of a 150x150 bitmap.
This code will do exactly that (c#):
using ( Image img = Image.FromStream( FU.PostedFile.InputStream ) )
{
int sourceWidth = img.Width;
int sourceHeight = img.Height;
int desiredHeight = 150;
int desiredWidth = 150;
double heightToWidthRatio = sourceHeight / ( double )sourceWidth;
//This draw method will always center the image horizonally or vertically, as appropriate
using ( Bitmap thumbnailBitmap = new Bitmap( desiredWidth, desiredHeight ) )
{
using ( Graphics thumbnailGraph = Graphics.FromImage( thumbnailBitmap ) )
{
thumbnailGraph.CompositingQuality = CompositingQuality.HighQuality;
thumbnailGraph.SmoothingMode = SmoothingMode.HighQuality;
thumbnailGraph.InterpolationMode = InterpolationMode.HighQualityBicubic;
float destWidth = ( heightToWidthRatio > 1f ) ? ( float )( desiredWidth / heightToWidthRatio ) : desiredWidth;
float destHeight = ( heightToWidthRatio > 1f ) ? desiredHeight : ( float )( desiredHeight * heightToWidthRatio );
float destX = ( desiredWidth - destWidth ) / 2f;
float destY = ( desiredHeight - destHeight ) / 2f;
thumbnailGraph.DrawImage( img, new RectangleF( destX, destY, destWidth, destHeight ),
new Rectangle( sourceWidth, sourceHeight, sourceWidth, sourceHeight ),
GraphicsUnit.Pixel );
}
}
}
Continue to write out the file as you have been, previously.
The important part is the four float values in the middle and the fact that it uses a RectangleF in the DrawImage function, to truly center, even on fractional values.
If you do not want that behavior due to excessive antialiasing, just Math.Floor the values and continue to use Rectangle and ints.
Related
Is there an easy way to save an image as a set 210px Height but the width will be proportionate. Eg. If the image is naturally 420 x 600 then it would resize/save as 210 x 300. The code I'm using is VB and is currently set to save it as 210x210..
Dim returnImage As System.Drawing.Image = Image.FromFile("D:\domains\example.com\httpdocs\catalog\images\" & imageFilename)
Dim thumb As System.Drawing.Image = FixedSize(returnImage, 210, 210)
I believe what you want to do is maintain the aspect ratio, this is the code I use:
Public Function ScaleImage(ByVal OldImage As System.Drawing.Image, ByVal TargetHeight As Integer, ByVal TargetWidth As Integer) As System.Drawing.Image
Dim NewHeight As Integer = TargetHeight
Dim NewWidth As Integer = NewHeight / OldImage.Height * OldImage.Width
If NewWidth > TargetWidth Then
NewWidth = TargetWidth
NewHeight = NewWidth / OldImage.Width * OldImage.Height
End If
Return New Bitmap(OldImage, NewWidth, NewHeight)
End Function
I need to perform median calculation in MS Report Builder 3.0, could anyone explain how I could achieve it considering my original value are
Region - Etab- Value
Abc - Def - 10
Abc - Def - 12
Ged - Tae - 1
I need to group by Region and Etab.
I've managed to get the proper values using hashtable the following way :
Dim theHashTable As New System.Collections.Hashtable
Function AddValue(theRapport As String, theRegion As String, theEtab As String, theRow As String, theValue As String) As Integer
Dim num As Integer
num = 0
If (theHashTable Is Nothing) Then
theHashTable = New System.Collections.Hashtable
End If
If Integer.TryParse(theValue, num) Then
If (num >= 0) Then
If (theHashTable.ContainsKey(theRapport)) Then
Dim regionHT As New System.Collections.Hashtable
regionHT = theHashTable(theRapport)
If (regionHT.ContainsKey(theRegion)) Then
Dim etabHT As New System.Collections.Hashtable
etabHT = regionHT(theRegion)
If (etabHT.ContainsKey(theEtab)) Then
Dim valueHT As New System.Collections.Hashtable
valueHT = etabHT(theEtab)
If (Not valueHT.ContainsKey(theRow)) Then
valueHT.Add(theRow, theValue)
End If
etabHT(theEtab) = valueHT
Else
Dim valueHT As New System.Collections.Hashtable
valueHT.Add(theRow, theValue)
etabHT.Add(theEtab, valueHT)
End If
regionHT(theRegion) = etabHT
Else
Dim etabHT As New System.Collections.Hashtable
Dim valueHT As New System.Collections.Hashtable
valueHT.Add(theRow, theValue)
etabHT.Add(theEtab, valueHT)
regionHT.Add(theRegion, etabHT)
End If
theHashTable(theRapport) = regionHT
Else
Dim regionHT As New System.Collections.Hashtable
Dim etabHT As New System.Collections.Hashtable
Dim valueHT As New System.Collections.Hashtable
valueHT.Add(theRow, theValue)
etabHT.Add(theEtab, valueHT)
regionHT.Add(theRegion, etabHT)
theHashTable.Add(theRapport, regionHT)
End If
End If
End If
Return num
End Function
Function GetMedian(theRapport As String, theRegion As String, theEtab As String) As String
Dim arrayInt As New System.Collections.ArrayList
arrayInt = GetArray(theRapport, theRegion, theEtab)
arrayInt.Sort()
Dim mid As Double = (arrayInt.Count - 1) / 2.0
Dim midInt As Integer = mid
Dim mid2Int As Integer = mid + 0.5
If arrayInt.Count >= 2 Then
Return ((arrayInt(midInt) + arrayInt(mid2Int)) / 2).ToString()
ElseIf arrayInt.Count = 1 Then
Return arrayInt(0)
Else
Return ""
End If
End Function
Function GetQ1(theRapport As String, theRegion As String, theEtab As String) As String
Dim arrayInt As New System.Collections.ArrayList
arrayInt = GetArray(theRapport, theRegion, theEtab)
arrayInt.Sort()
Dim taille As Integer = arrayInt.Count
If (taille = 1) Then
Return arrayInt(0)
ElseIf ((taille Mod 2) = 0 And taille > 0) Then
Dim mid1 As Integer = taille / 2
Dim midmid As Integer = mid1 / 2
If (mid1 Mod 2 = 0) Then
Return ((arrayInt(midmid - 1) + arrayInt(midmid)) / 2).ToString()
Else
Return (arrayInt(midmid)).ToString()
End If
ElseIf (taille = 1) Then
Return arrayInt(1)
ElseIf ((taille - 1) Mod 4 = 0) Then
Dim n As Integer = (taille - 1) / 4
Return ((arrayInt(n - 1) * 0.25 + arrayInt(n) * 0.75)).ToString()
ElseIf ((taille - 3) Mod 4 = 0) Then
Dim n As Integer = (taille - 3) / 4
Return ((arrayInt(n) * 0.75 + arrayInt(n + 1) * 0.25)).ToString()
Else
Return ""
End If
End Function
Function GetQ3(theRapport As String, theRegion As String, theEtab As String) As String
Dim arrayInt As New System.Collections.ArrayList
arrayInt = GetArray(theRapport, theRegion, theEtab)
arrayInt.Sort()
Dim taille As Integer = arrayInt.Count
If (taille = 1) Then
Return arrayInt(0)
ElseIf ((taille Mod 2) = 0 And taille > 0) Then
Dim mid1 As Integer = taille / 2
Dim midmid As Integer = mid1 / 2
If (mid1 Mod 2 = 0) Then
Return ((arrayInt(mid1 + midmid - 1) + arrayInt(mid1 + midmid)) / 2).ToString()
Else
Return (arrayInt(mid1 + midmid)).ToString()
End If
ElseIf (taille = 1) Then
Return arrayInt(1)
ElseIf ((taille - 1) Mod 4 = 0) Then
Dim n As Integer = (taille - 1) / 4
Return ((arrayInt(3 * n) * 0.75 + arrayInt(3 * n + 1) * 0.25)).ToString()
ElseIf ((taille - 3) Mod 4 = 0) Then
Dim n As Integer = (taille - 3) / 4
Return ((arrayInt(3 * n + 1) * 0.25 + arrayInt(3 * n + 2) * 0.75)).ToString()
Else
Return ""
End If
End Function
Function GetArray(theRapport As String, theRegion As String, theEtab As String) As System.Collections.ArrayList
Dim arrayInt As New System.Collections.ArrayList
If (theHashTable Is Nothing Or theHashTable.Count = 0) Then
Return arrayInt
Else
If (theHashTable.ContainsKey(theRapport)) Then
Dim regionHT As System.Collections.Hashtable
regionHT = theHashTable(theRapport)
If (theRegion = "" And theEtab = "") Then
For Each value As System.Collections.Hashtable In regionHT.Values
For Each value2 As System.Collections.Hashtable In value.Values
For Each valeur As Integer In value2.Values
arrayInt.Add(valeur)
Next
Next
Next
ElseIf (regionHT.ContainsKey(theRegion) And theEtab = "") Then
Dim etabHT As System.Collections.Hashtable
etabHT = regionHT(theRegion)
For Each value As System.Collections.Hashtable In etabHT.Values
For Each valeur As Integer In value.Values
arrayInt.Add(valeur)
Next
Next
ElseIf (regionHT.ContainsKey(theRegion) And theEtab <> "") Then
Dim etabHT As System.Collections.Hashtable
etabHT = regionHT(theRegion)
If Not (etabHT Is Nothing Or etabHT.Count = 0) Then
If (etabHT.ContainsKey(theEtab)) Then
Dim valuesHT As System.Collections.Hashtable
valuesHT = etabHT(theEtab)
For Each value As Integer In valuesHT.Values
arrayInt.Add(value)
Next
End If
End If
End If
End If
Return arrayInt
End If
End Function
Function PrintArray(theRapport As String, theRegion As String, theEtab As String) As String
Dim arrayInt As New System.Collections.ArrayList
arrayInt = GetArray(theRapport, theRegion, theEtab)
Dim str As String = ""
If (arrayInt.Count > 0) Then
str = String.Join(" | ", arrayInt.ToArray)
Else
str = " "
End If
Return str
End Function
The first hashtable is for different tables of the report needing the median.
I then use the following command to add value
Code.AddValue("3_2",Fields!Region.Value,Fields!Etablissement.Value,Fields!rowNumber.Value,Fields!Value.Value)
Then I get the median using the expressions
=Code.GetMedian("3_2", Fields!Region.Value,Fields!Etablissement.Value)
=Code.GetMedian("3_2", Fields!Region.Value,"")
=Code.GetMedian("3_2", "","")
I've tried placing the AddValue fonction on a hidden table and in the summary row of the tables.
I get the proper value but as soon as I expand or collapse a row everything is change to blank. How can I keep the value or where could I put the AddValue function to make sure it is called on every action, for every table in the report ?
Thanks
I want to store bitmap image to byte, but in run time i'm getting error like
Conversion From type Image Format to Type Integer is Not Valid
Please Any one Help Me
For Each file As UploadedFile In` DOC.UploadedFiles`
Context.Cache.Remove(Session.SessionID + "UploadedFile")
Dim stream As Stream = file.InputStream
GenerateThumbnails(0.5, stream)
Dim DocumentImgName = file.FileName
Dim imgData As Byte() = New Byte(ViewState("CompressedImageData")) {}
Dim DocumentSplit = DocumentImgName.Split(".")
Dim ImgName = DocumentSplit(0)
Dim ImgExt = DocumentSplit(1)
stream.Read(imgData, 0, imgData.Length)
ViewState("imgData") = imgData
ViewState("FileName") = ImgName
ViewState("FileExtension") = ImgExt
Dim ms As New MemoryStream()
ms.Write(imgData, 0, imgData.Length)
Next
Private Sub GenerateThumbnails(ByVal scaleFactor As Double, ByVal sourcePath As Stream)
Using image__1 = Image.FromStream(sourcePath)
' can given width of image as we want
Dim newWidth = CInt(image__1.Width * scaleFactor)
' can given height of image as we want
Dim newHeight = CInt(image__1.Height * scaleFactor)
Dim thumbnailImg = New Bitmap(newWidth, newHeight)
Dim thumbGraph = Graphics.FromImage(thumbnailImg)
thumbGraph.CompositingQuality = CompositingQuality.HighQuality
thumbGraph.SmoothingMode = SmoothingMode.HighQuality
thumbGraph.InterpolationMode = InterpolationMode.HighQualityBicubic
Dim imageRectangle = New Rectangle(0, 0, newWidth, newHeight)
thumbGraph.DrawImage(image__1, imageRectangle)
ViewState("CompressedImageData") = image__1.RawFormat
End Using
End Sub
You Can Store an Image data after Convert it to Byte datatype as below:
Dim ms As New Syste.IO.MemoryStream
Me.PictureBox1.Image.Save(ms, PictureBox1.Image.RawFormat)
Dim byteImage() As Byte = ms.ToArray
Then You can Store The byteImage() to a field wich its type is Image Or Varbinary.
I have the following code in my IHttpHandler:
Dim MemoryStream1 As New System.IO.MemoryStream
MemoryStream1.Write(SqlDataReader1("cover"), 0, SqlDataReader1("cover").Length - 1)
Dim Bitmap1 As System.Drawing.Bitmap = System.Drawing.Bitmap.FromStream(MemoryStream1)
Dim Width1 As Integer = Bitmap1.Width
Dim Height1 As Integer = Bitmap1.Height
Dim Width2 As Integer = 90
Dim Height2 As Integer = Height1 * Width1 / Width1
Dim Bitmap2 As System.Drawing.Bitmap = New System.Drawing.Bitmap(Width2, Height2)
Dim Graphics1 As System.Drawing.Graphics = System.Drawing.Graphics.FromImage(Bitmap2)
Graphics1.DrawImage(Bitmap1, 0, 0, Width2, Height2)
Dim MemoryStream2 As New System.IO.MemoryStream
Bitmap2.Save(MemoryStream2, System.Drawing.Imaging.ImageFormat.Png)
context.Response.BinaryWrite(MemoryStream2.ToArray)
It works but I'm not sure that it is the right way to resize an image. How to simplify that code?
Thanks in advance!
Public Function ResizeImage(imgToResize As Image, size As Size) As Byte()
Dim sourceWidth As Integer = imgToResize.Width
Dim sourceHeight As Integer = imgToResize.Height
Dim nPercent As Single = 0
Dim nPercentW As Single = 0
Dim nPercentH As Single = 0
nPercentW = (CSng(size.Width) / CSng(sourceWidth))
nPercentH = (CSng(size.Height) / CSng(sourceHeight))
If nPercentH < nPercentW Then
nPercent = nPercentH
Else
nPercent = nPercentW
End If
Dim destWidth As Integer = CInt(Math.Truncate(sourceWidth * nPercent))
Dim destHeight As Integer = CInt(Math.Truncate(sourceHeight * nPercent))
Dim b As New Bitmap(destWidth, destHeight)
Dim g As Graphics = Graphics.FromImage(DirectCast(b, Image))
g.InterpolationMode = InterpolationMode.HighQualityBicubic
g.DrawImage(imgToResize, 0, 0, destWidth, destHeight)
g.Dispose()
Return b.ToByteArray()
End Function
This function will resize an image to a specified size keeping its proporstion. It was in C# and I put it through an online converter so may not be 100% correct
ToByteArray() is an extension method I wrote to store the image in a DB i can give you that also if you like.
Basically the code is correct, but there are some problems with it:
You are skipping the last byte when you write into the first memory stream. The last property in the Write call should be the length, not the length minus one.
Your calculation of Height2 is incorrect. The expression Height1 * Width1 / Width1 will always evaluate to the value of Height1. You should use Height1 * Width2 / Width1 instead.
You are not disposing your memory streams, bitmaps or graphics objects. Use Using blocks to make sure that the objects are disposed.
You can simplify the code somewhat by creating the first memory stream from the byte array instead of writing the array to the stream:
Using MemoryStream1 As New System.IO.MemoryStream(SqlDataReader1("cover"))
Using Bitmap1 As System.Drawing.Bitmap = System.Drawing.Bitmap.FromStream(MemoryStream1)
Dim Width1 As Integer = Bitmap1.Width
Dim Height1 As Integer = Bitmap1.Height
Dim Width2 As Integer = 90
Dim Height2 As Integer = Height1 * Width2 / Width1
Using Bitmap2 As System.Drawing.Bitmap = New System.Drawing.Bitmap(Width2, Height2)
Using Graphics1 As System.Drawing.Graphics = System.Drawing.Graphics.FromImage(Bitmap2)
Graphics1.DrawImage(Bitmap1, 0, 0, Width2, Height2)
End Using
Using MemoryStream2 As New System.IO.MemoryStream
Bitmap2.Save(MemoryStream2, System.Drawing.Imaging.ImageFormat.Png)
context.Response.BinaryWrite(MemoryStream2.ToArray)
End Using
End Using
End Using
End Using
i was searching google for some kind solution and i found one, i tried to implement it in my code but it doesn't work. The problem is that after resizing white images they gets gray border.
Here is the link of soloution i found:
It says:
This problem is occuring because you are interpolating your image data to a
new size, but along the edges there are no pixels to interpolate and .NET
uses black pixels for these edges by default. To fix this you need to use an
ImageAttributes class in your DrawImage call....
https://groups.google.com/group/microsoft.public.dotnet.framework.drawing/browse_thread/thread/d834851b49274fd9/81a4fd43694457ac?hl=en&lnk=st&q=DrawImage+resized+border#81a4fd43694457ac
CODE 1: And this is my code WITH IMPLEMENTATION OF ImageAttributes:
Private Shared Function ResizeImageFile(ByVal imageFile As Byte(), ByVal targetSize As Integer) As Byte()
Using oldImage As System.Drawing.Image = System.Drawing.Image.FromStream(New MemoryStream(imageFile))
Dim newSize As Size = CalculateDimensions(oldImage.Size, targetSize)
Using newImage As New Bitmap(newSize.Width, newSize.Height, PixelFormat.Format32bppRgb)
Using canvas As Graphics = Graphics.FromImage(newImage)
Using ia As New ImageAttributes
ia.SetWrapMode(Drawing2D.WrapMode.TileFlipXY)
canvas.SmoothingMode = SmoothingMode.AntiAlias
canvas.InterpolationMode = InterpolationMode.HighQualityBicubic
canvas.PixelOffsetMode = PixelOffsetMode.HighQuality
canvas.DrawImage(oldImage, New Rectangle(New Point(0, 0), newSize), 0, 0, newImage.Width, newImage.Height, GraphicsUnit.Pixel, ia)
Dim m As New MemoryStream()
newImage.Save(m, ImageFormat.Png)
Return m.GetBuffer()
End Using
End Using
End Using
End Using
End Function
Private Shared Function CalculateDimensions(ByVal oldSize As Size, ByVal targetSize As Integer) As Size
Dim newSize As New Size()
If oldSize.Height > oldSize.Width Then
newSize.Width = CInt((oldSize.Width * (CSng(targetSize) / CSng(oldSize.Height))))
newSize.Height = targetSize
Else
newSize.Width = targetSize
newSize.Height = CInt((oldSize.Height * (CSng(targetSize) / CSng(oldSize.Width))))
End If
Return newSize
End Function
CODE 2: CODE THAT COUSES A GRAY BORDER ON WHITE IMAGE
Here is the image after resizing:
new image size in width = 400px
Private Shared Function ResizeImageFile(ByVal imageFile As Byte(), ByVal targetSize As Integer) As Byte()
Using oldImage As System.Drawing.Image = System.Drawing.Image.FromStream(New MemoryStream(imageFile))
Dim newSize As Size = CalculateDimensions(oldImage.Size, targetSize)
Using newImage As New Bitmap(newSize.Width, newSize.Height, PixelFormat.Format32bppRgb)
Using canvas As Graphics = Graphics.FromImage(newImage)
canvas.SmoothingMode = SmoothingMode.AntiAlias
canvas.InterpolationMode = InterpolationMode.HighQualityBicubic
canvas.PixelOffsetMode = PixelOffsetMode.HighQuality
canvas.DrawImage(oldImage, New Rectangle(New Point(0, 0), newSize))
Dim m As New MemoryStream()
newImage.Save(m, ImageFormat.Png)
Return m.GetBuffer()
End Using
End Using
End Using
End Function
Private Shared Function CalculateDimensions(ByVal oldSize As Size, ByVal targetSize As Integer) As Size
Dim newSize As New Size()
If oldSize.Height > oldSize.Width Then
newSize.Width = CInt((oldSize.Width * (CSng(targetSize) / CSng(oldSize.Height))))
newSize.Height = targetSize
Else
newSize.Width = targetSize
newSize.Height = CInt((oldSize.Height * (CSng(targetSize) / CSng(oldSize.Width))))
End If
Return newSize
End Function
UPDATE 30.07.2011.:
CODE 1 solved the problem with the gray borders on white images, but there is new problem. The problem is in this line of code:
canvas.DrawImage(oldImage, New Rectangle(New Point(0, 0), newSize), 0, 0, newImage.Width, newImage.Height, GraphicsUnit.Pixel, ia)
With this code I get output image with desired width and height and without gray borders but the oldImage isn't scaled.
For example:
If I want to upload, resize and save the image that is orginaly for instance 640x480px and that the targetSize is 400px. As output I get an image that is width: 400px, height: 300px, without gray borders, but oldImage isn't resized/scaled to 400px. Insted of this, oldImage is drawn with the original resolution. How to scale oldImage to be drawn correctly? Can someone point me to the right solution or modify the code?
Thanx to everyone, but I found the solution to all my problems.
The CODE 1 didn't work correctly because of the following line of code:
canvas.DrawImage(oldImage, New Rectangle(New Point(0, 0), newSize), 0, 0, newImage.Width, newImage.Height, GraphicsUnit.Pixel, ia)
SOLUTION:
canvas.DrawImage(oldImage, New Rectangle(New Point(0, 0), newSize), 0, 0, oldImage.Width, oldImage.Height, GraphicsUnit.Pixel, ia)
HERE IS THE FULL WORKING CODE (resized image without gray/black borders):
Private Shared Function ResizeImageFile(ByVal imageFile As Byte(), ByVal targetSize As Integer) As Byte()
Using oldImage As System.Drawing.Image = System.Drawing.Image.FromStream(New MemoryStream(imageFile))
Dim newSize As Size = CalculateDimensions(oldImage.Size, targetSize)
Using newImage As New Bitmap(newSize.Width, newSize.Height, PixelFormat.Format32bppRgb)
Using canvas As Graphics = Graphics.FromImage(newImage)
Using ia As New ImageAttributes
ia.SetWrapMode(Drawing2D.WrapMode.TileFlipXY)
canvas.SmoothingMode = SmoothingMode.AntiAlias
canvas.InterpolationMode = InterpolationMode.HighQualityBicubic
canvas.PixelOffsetMode = PixelOffsetMode.HighQuality
canvas.DrawImage(oldImage, New Rectangle(New Point(0, 0), newSize), 0, 0, oldImage.Width, oldImage.Height, GraphicsUnit.Pixel, ia)
Dim m As New MemoryStream()
newImage.Save(m, ImageFormat.Png)
Return m.GetBuffer()
End Using
End Using
End Using
End Using
End Function
Private Shared Function CalculateDimensions(ByVal oldSize As Size, ByVal targetSize As Integer) As Size
Dim newSize As New Size()
If oldSize.Height > oldSize.Width Then
newSize.Width = CInt((oldSize.Width * (CSng(targetSize) / CSng(oldSize.Height))))
newSize.Height = targetSize
Else
newSize.Width = targetSize
newSize.Height = CInt((oldSize.Height * (CSng(targetSize) / CSng(oldSize.Width))))
End If
Return newSize
End Function
Here is a function out of a class I have, you will have to replace some of the class Properties(ThumbNailSize.Width, ThumbNailSize.Height):
public void ResizeImage(HttpPostedFile fil, string sPhysicalPath,
string sOrgFileName,string sThumbNailFileName,
ImageFormat oFormat, int rez)
{
try
{
System.Drawing.Image oImg = System.Drawing.Image.FromStream(fil.InputStream);
decimal pixtosubstract = 0;
decimal percentage;
//default
Size ThumbNailSizeToUse = new Size();
if (ThumbNailSize.Width < oImg.Size.Width || ThumbNailSize.Height < oImg.Size.Height)
{
if (oImg.Size.Width > oImg.Size.Height)
{
percentage = (((decimal)oImg.Size.Width - (decimal)ThumbNailSize.Width) / (decimal)oImg.Size.Width);
pixtosubstract = percentage * oImg.Size.Height;
ThumbNailSizeToUse.Width = ThumbNailSize.Width;
ThumbNailSizeToUse.Height = oImg.Size.Height - (int)pixtosubstract;
}
else
{
percentage = (((decimal)oImg.Size.Height - (decimal)ThumbNailSize.Height) / (decimal)oImg.Size.Height);
pixtosubstract = percentage * (decimal)oImg.Size.Width;
ThumbNailSizeToUse.Height = ThumbNailSize.Height;
ThumbNailSizeToUse.Width = oImg.Size.Width - (int)pixtosubstract;
}
}
else
{
ThumbNailSizeToUse.Width = oImg.Size.Width;
ThumbNailSizeToUse.Height = oImg.Size.Height;
}
Bitmap bmp = new Bitmap(ThumbNailSizeToUse.Width, ThumbNailSizeToUse.Height);
bmp.SetResolution(rez, rez);
System.Drawing.Image oThumbNail = bmp;
bmp = null;
Graphics oGraphic = Graphics.FromImage(oThumbNail);
oGraphic.CompositingQuality = CompositingQuality.HighQuality;
oGraphic.SmoothingMode = SmoothingMode.HighQuality;
oGraphic.InterpolationMode = InterpolationMode.HighQualityBicubic;
Rectangle oRectangle = new Rectangle(0, 0, ThumbNailSizeToUse.Width, ThumbNailSizeToUse.Height);
oGraphic.DrawImage(oImg, oRectangle);
oThumbNail.Save(sPhysicalPath + sThumbNailFileName, oFormat);
oImg.Dispose();
}
catch (Exception ex)
{
Response.Write(ex.Message);
}
}