Saving an image as 120 Height x Proportionate Width - VB - asp.net

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

Related

Finding specific shape's RunProperty (pptx)

I only want to get the font sizes from the title shapes, but my code checks all the shape's RunProperties:
Public Function GetSlideTitle(ByVal slidePart As SlidePart) As String()
If (Not (slidePart.Slide) Is Nothing) Then
' Find all the title shapes.
Dim shapes = From shape In slidePart.Slide.Descendants(Of Shape)() _
Where (IsTitleShape(shape)) _
Select shape
Dim paragraphText As StringBuilder = New StringBuilder
Dim minFont As Double = 200000
Dim maxfont As Double = 0
''''getting the text from the title shapes - this works fine
For Each shape As Object In shapes
For Each paragraph As Drawing.Paragraph In shape.TextBody.Descendants(Of D.Paragraph)()
For Each text As Object In paragraph.Descendants(Of D.Text)()
paragraphText.Append(text.Text)
Next
Next
Next
'''' This is the part in question:
Dim runProList As Drawing.RunProperties() = slidePart.Slide.Descendants(Of Drawing.RunProperties)().ToArray()
For Each r As Drawing.RunProperties In runProList
If Not IsNothing(r) AndAlso Not IsNothing(r.FontSize) Then
If r.FontSize.Value > 0 AndAlso minFont > r.FontSize.Value Then minFont = r.FontSize.Value
If maxfont < r.FontSize.Value Then maxfont = r.FontSize.Value
End If
Next
Return New String() {paragraphText.ToString, minFont.ToString, maxfont.ToString}
End If
Return New String() {String.Empty}
End Function
How do I know which RunProperty belongs to a given shape?

Conversion of BitmapImage to Byte array and Store it Into Sql Database

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.

image resize and crop on upload asp,net

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.

Resizing an image in VB.NET

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

After resizing white image gets gray border

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);
}
}

Resources