VB.net crop an image (jpg) like ms paint with no quality loss - vb.net

Given an jpg image slightly larger than 19" x 23" I need to crop it to exactly 19" x 23" and preserve the original quality using VB.NET.
I can do this in MS paint, If I open a 2851 x 4651 200 DPI jpg and use the Image Properties dialog I can change the width and Height to 3800 x 4600 (exactly 19" x 23" # 200 DPI).
The resultant image is identical to the original in quality and compression but is cropped on the right and bottom by the 51 pixels. The file size is slightly smaller as expected.
When I use the many techniques I have found on SO to crop/resize an image when I save the image it always saves as 96 DPI. I can adjust the width and height to accommodate the 96 DPI so the end result is exactly 19" x 23", however the resulting pixilation is higher than the original, and the files size is considerably smaller, so obvious quality loss.
What I want is to do is (a simple?) crop like MS paint does. Just take a little off the side and bottom, but I cannot seem to save an image with anything other than 96 DPI.
If I can figure out how to the save the cropped file at 200 DPI (or whatever the original image was) I think what I have will work fine.
I am willing to use an external library if that is what it takes.
Here is one example that works in the sense that the resulting image is 19" x 23" and the image is actually scaled preserving the aspect ratio, however the quality is less than the original.
This code is from another SO answer with some minor modifications.
Public Shared Function ResizeImage(SourceImage As Drawing.Image, TargetWidthIn As Decimal, TargetHeightIn As Decimal) As Drawing.Bitmap
'Dim TargetWidth As Integer = TargetWidthIn * SourceImage.HorizontalResolution
'Dim TargetHeight As Integer = TargetHeightIn * SourceImage.VerticalResolution
Dim TargetWidth As Integer = TargetWidthIn * 96
Dim TargetHeight As Integer = TargetHeightIn * 96
Dim bmSource = New Drawing.Bitmap(SourceImage)
Dim bmDest As New Drawing.Bitmap(TargetWidth, TargetHeight, Drawing.Imaging.PixelFormat.Format32bppArgb)
Dim nSourceAspectRatio = bmSource.Width / bmSource.Height
Dim nDestAspectRatio = bmDest.Width / bmDest.Height
Dim NewX = 0
Dim NewY = 0
Dim NewWidth = bmDest.Width
Dim NewHeight = bmDest.Height
If nDestAspectRatio = nSourceAspectRatio Then
'same ratio
ElseIf nDestAspectRatio > nSourceAspectRatio Then
'Source is taller
NewWidth = Convert.ToInt32(Math.Floor(nSourceAspectRatio * NewHeight))
NewX = Convert.ToInt32(Math.Floor((bmDest.Width - NewWidth) / 2))
Else
'Source is wider
NewHeight = Convert.ToInt32(Math.Floor((1 / nSourceAspectRatio) * NewWidth))
NewY = Convert.ToInt32(Math.Floor((bmDest.Height - NewHeight) / 2))
End If
Using grDest = Drawing.Graphics.FromImage(bmDest)
With grDest
.CompositingQuality = Drawing.Drawing2D.CompositingQuality.HighQuality
'.InterpolationMode = Drawing.Drawing2D.InterpolationMode.HighQualityBicubic
.InterpolationMode = Drawing.Drawing2D.InterpolationMode.NearestNeighbor
.PixelOffsetMode = Drawing.Drawing2D.PixelOffsetMode.HighQuality
.CompositingMode = Drawing.Drawing2D.CompositingMode.SourceCopy
'.SmoothingMode = Drawing.Drawing2D.SmoothingMode.AntiAlias
'.CompositingMode = Drawing.Drawing2D.CompositingMode.SourceOver
.DrawImage(bmSource, NewX, NewY, NewWidth, NewHeight)
End With
End Using
Return bmDest
End Function

I found a solution on SO here
I modifyed my original code above to keep the DPI of the original image:
Dim TargetWidth As Integer = TargetWidthIn * SourceImage.HorizontalResolution
Dim TargetHeight As Integer = TargetHeightIn * SourceImage.VerticalResolution
Then after the call to ResizeImage:
Select Case imageType.ToLower
Case "jpg"
Dim jpgEncoder As ImageCodecInfo = GetEncoder(ImageFormat.Jpeg)
Dim myEncoder As System.Drawing.Imaging.Encoder = System.Drawing.Imaging.Encoder.Quality
Dim myEncoderParams As New EncoderParameters(1)
Dim myEncoderQuality As New EncoderParameter(myEncoder, CType(98L, Int32)) '98%
myEncoderParams.Param(0) = myEncoderQuality
bm.SetResolution(img.HorizontalResolution, img.VerticalResolution)
bm.Save(tempfile, jpgEncoder, myEncoderParams)
Case "png", "gif"
bm.Save(tempfile, System.Drawing.Imaging.ImageFormat.Png)
Case "tiff", "tif"
bm.Save(tempfile, System.Drawing.Imaging.ImageFormat.Tiff)
Case Else
bm.Save(tempfile, System.Drawing.Imaging.ImageFormat.Png)
End Select
bm.Dispose()
I only use jpg now so I don't know if the tiff and png parts work, but it seems using the jpeg encoder allowed me to save the file with 200 DPI and maintain the original quality.
Here is the GetEncoder part that is missing from the other post:
Private Shared Function GetEncoder(f As Drawing.Imaging.ImageFormat) As ImageCodecInfo
Dim myEncoders() As ImageCodecInfo
myEncoders = ImageCodecInfo.GetImageEncoders()
Dim numEncoders As Integer = myEncoders.GetLength(0)
Dim strNumEncoders As String = numEncoders.ToString()
' Get the info. for all encoders in the array.
If numEncoders > 0 Then
Dim myEncoderInfo(numEncoders * 10) As String
For i As Integer = 0 To numEncoders - 1
If myEncoders(i).FilenameExtension.Contains(f.ToString.ToUpper) Then
Return myEncoders(i)
End If
Next
End If
Return Nothing

Related

How Can I re-size an image in VB.Net

I need it so that in my code if something evaluates to true it changes the image location and size.
This is my code so far:
With picValueTwentySix
.Location = New Point(302, 134)
.Size = New System.Drawing.Size(169, 40)
.SizeMode = PictureBoxSizeMode.Zoom
End With
Anybody know why it isn't re-sizing?
Thanks!
As everyone has already mentioned, you need to work the the image. Here is a function I made up for ease of use.
Public Function ResizeImage(ByVal image As Image, ByVal size As Size, Optional ByVal preserveAspectRatio As Boolean = True) As Image
Try
Dim newWidth As Integer
Dim newHeight As Integer
If preserveAspectRatio Then
Dim originalWidth As Integer = image.Width
Dim originalHeight As Integer = image.Height
Dim percentWidth As Single = CSng(size.Width) / CSng(originalWidth)
Dim percentHeight As Single = CSng(size.Height) / CSng(originalHeight)
Dim percent As Single = IIf(percentHeight < percentWidth, percentHeight, percentWidth)
newWidth = CInt(originalWidth * percent)
newHeight = CInt(originalHeight * percent)
Else
newWidth = size.Width
newHeight = size.Height
End If
Dim newImage As Image = New Bitmap(newWidth, newHeight)
Using graphicsHandle As Graphics = Graphics.FromImage(newImage)
graphicsHandle.InterpolationMode = InterpolationMode.HighQualityBicubic
graphicsHandle.DrawImage(image, 0, 0, newWidth, newHeight)
End Using
Return newImage
Catch ex As Exception
Return image
End Try
End Function
Basically it creates a new blank graphic to the dimensions you request, then copies the original image to it while scaling it to fit. I think if you step throw it a line at a time you should be pretty self explanatory, but ask if you have questions...
As stated by #Plutonix, changing the Picturebox size will not affect the image size itself, you have to make sure the actual image size is bigger than the size of the picture box, set the size mode of the picturebox to stretchimage, in this case once you resize the picture box the change will reflect. Also refresh the picture box after resizing.

vb.net Image Manipulation

I was tasked today after creating a program to Add watermarks to also create one to remove that same watermark.
My thoughts are that it is now part of the image and can't be removed so easily.
Is this accurate or is the actually a way? ( that doesnt take 10 years)
thanks for any hints
Here is my code to add the watermarks:
Dim watermark_bm As Bitmap = Global.AnchorAuditor.My.Resources.Logo_White
Dim watermark_bm2 As Bitmap = Global.AnchorAuditor.My.Resources.CLS_Logo_White_Engineering
'watermark_bm2.MakeTransparent()
' WATERMARK IMAGE 1 - AA
Using str As Stream = File.OpenRead(s)
Dim or_bm As Bitmap = Image.FromStream(str)
'''''''''''''''''''''''''START IMAGE 1''''''''''''''''''''''''''
or_bm.SetResolution(20, 20)
Dim x1 As Integer = or_bm.Width - 300
Dim Y As Integer = or_bm.Height - 300
Const ALPHA As Byte = 128
' Set the watermark's pixels' Alpha components.
Dim clr As Color
For py As Integer = 0 To watermark_bm.Height - 1
For px As Integer = 0 To watermark_bm.Width - 1
clr = watermark_bm.GetPixel(px, py)
watermark_bm.SetPixel(px, py, _
Color.FromArgb(ALPHA, clr.R, clr.G, clr.B))
Next px
Next py
' Set the watermark's transparent color.
watermark_bm.MakeTransparent(watermark_bm.GetPixel(0, _
0))
' Copy onto the result image.
Dim gr As Graphics = Graphics.FromImage(or_bm)
gr.DrawImage(watermark_bm, x1, Y)
'''''''''''''''''''''''''END IMAGE 1 START IMAGE 2''''''''''''''''''''''''''
or_bm.SetResolution(60, 60)
Dim x2 As Integer = 75
Dim Y1 As Integer = 75
Const ALPHA1 As Byte = 128
' Set the watermark's pixels' Alpha components.
Dim clr1 As Color
For py As Integer = 0 To watermark_bm2.Height - 1
For px As Integer = 0 To watermark_bm2.Width - 1
clr1 = watermark_bm2.GetPixel(px, py)
watermark_bm2.SetPixel(px, py, _
Color.FromArgb(ALPHA1, clr1.R, clr1.G, clr1.B))
Next px
Next py
' Set the watermark's transparent color.
watermark_bm2.MakeTransparent(watermark_bm2.GetPixel(0, _
0))
' Copy onto the result image.
Dim gr1 As Graphics = Graphics.FromImage(or_bm)
gr1.DrawImage(watermark_bm2, x2, Y1)
''''''''''''''''''''''''END IMAGE 2'''''''''''''''''''''''''''
or_bm.Save(s & "deleteme.jpg", _
System.Drawing.Imaging.ImageFormat.Jpeg)
End Using
You're correct - adding a watermark is far easier than removing it. The standard approach is to keep a copy of the original someplace and use that instead of trying to manipulate the image afterwards.

VB.NET - Create An Image - Resize But Add Background To Remainding Space

I am attempting to resize an image to specific dimensions but I do not want to stretch the image at all if it is smaller than my chosen dimensions. Instead I want to add a black background around the image area that is not in use.
I think that the easiest way to do this would be to create a new image of my desired dimensions & set a background color & then add & center the image over top of this background.
I have created a Bitmap using:
Dim bmp As New Drawing.Bitmap(500, 500)
Dim grap As Drawing.Graphics = Drawing.Graphics.FromImage(bmp)
grap.Clear(Drawing.Color.Black)
From this point I got a bit lost on how to complete the process, all that is needed is to add an image to the Bitmap & center.
Any ideas would be much appretiated
I haven't tested this but it looks like you've pretty much got what you want but:
grap.Clear(Drawing.Color.Black)
Will surely just wipe the entire graphic back to black.
Try doing the clear prior to drawing image:
Graphics pic = this.CreateGraphics();
pic.Clear(Color.Black);
pic.DrawImage(img, new Point(center));
Ended up using:
' Load Image
Dim FilePath As String = "testimage.jpg"
Dim OriginalImage As New Bitmap(FilePath)
' Resize Image While Maintaining Aspect Ratio
Dim aspectRatio As Double
Dim newHeight As Integer
Dim newWidth As Integer
Dim maxWidth As Integer = 500
Dim maxHeight As Integer = 500
' Calculate Size
If OriginalImage.Width > maxWidth Or OriginalImage.Height > maxHeight Then
If OriginalImage.Width >= OriginalImage.Height Then ' image is wider than tall
newWidth = maxWidth
aspectRatio = OriginalImage.Width / maxWidth
newHeight = CInt(OriginalImage.Height / aspectRatio)
Else ' image is taller than wide
newHeight = maxHeight
aspectRatio = OriginalImage.Height / maxHeight
newWidth = CInt(OriginalImage.Width / aspectRatio)
End If
Else ' if image is not larger than max then increase size
If OriginalImage.Width > OriginalImage.Height Then
newWidth = maxWidth
aspectRatio = OriginalImage.Width / maxWidth
newHeight = CInt(OriginalImage.Height / aspectRatio)
Else
newHeight = maxHeight
aspectRatio = OriginalImage.Height / maxHeight
newWidth = CInt(OriginalImage.Width / aspectRatio)
End If
' Below keeps original height & width instead of resizing to fit new height / width
' newWidth = OriginalImage.Width
' newHeight = OriginalImage.Height
End If
Dim newImg As New Bitmap(OriginalImage, CInt(newWidth), CInt(newHeight)) '' blank canvas
' Create New Bitmap
Dim bmp As New Drawing.Bitmap(500, 500)
Dim grap As Drawing.Graphics = Drawing.Graphics.FromImage(bmp)
grap.Clear(Drawing.Color.Black)
Dim g As Graphics = Graphics.FromImage(bmp)
' Calculate Points To Insert Resized Image
Dim InsertX As Integer
Dim InsertY As Integer
' Calculate Y Axis Point
If newImg.Height >= 500 Then
InsertY = 0
Else
InsertY = CInt(((500 - newImg.Height) / 2))
End If
' Calculate X Axis Point
If newImg.Width >= 500 Then
InsertX = 0
Else
InsertX = CInt(((500 - newImg.Width) / 2))
End If
' Add Resized Image To Canvas
g.DrawImage(newImg, New Point(InsertX, InsertY))
By using just the ratio of the larger axis, you can fail in the situation that the other ratio forces you to exceed the other axis.
i.e. 1400x1000 ->( i want to fit into 300x200) -> but just with 1400/300 ratio (4.6) the result will be 300x214.
I think it would be useful to check both ratios and continue with the bigger

Reading pixel value of an image

Q> If showing all the RGB pixel value of a 60*66 PNG image takes 10-34 seconds then how Image Viewer shows image instantly ?
Dim clr As Integer ' or string
Dim xmax As Integer
Dim ymax As Integer
Dim x As Integer
Dim y As Integer
Dim bm As New Bitmap(dlgOpen.FileName)
xmax = bm.Width - 1
ymax = bm.Height - 1
For y = 0 To ymax
For x = 0 To xmax
With bm.GetPixel(x, y)
clr = .R & .G & .B
txtValue.AppendText(clr)
End With
Next x
Next y
Edit
Dim bmp As New Bitmap(dlgOpen.FileName)
Dim rect As New Rectangle(0, 0, bmp.Width, bmp.Height)
Dim bmpData As System.Drawing.Imaging.BitmapData = bmp.LockBits(rect,Drawing.Imaging.ImageLockMode.ReadWrite, bmp.PixelFormat)
Dim ptr As IntPtr = bmpData.Scan0
Dim bytes As Integer = Math.Abs(bmpData.Stride) * bmp.Height
Dim rgbValues(bytes - 1) As Byte
System.Runtime.InteropServices.Marshal.Copy(ptr, rgbValues, 0, bytes)
For counter As Integer = 0 To rgbValues.Length - 1
txtValue.AppendText(rgbValues(counter))
Next
System.Runtime.InteropServices.Marshal.Copy(rgbValues, 0, ptr, bytes)
bmp.UnlockBits(bmpData)
The first code takes 10 seconds and the 2nd one around 34 seconds for showing all the value in a textbox for a 59*66 PNG image on AMD A6 3500 with 4 GB RAM !
The problem exist when reading from file and writing to a textbox takes place in same time !
The problem is that the feature you're using, GetPixel, is very slow if you need to access a lot of pixels. Try using LockBits. You can use that to gather image data nearly instantly.
Using the LockBits method to access image data.

itextsharp: forcing image to take up entire width in vb.net

the following is a generated PDF with a few images. how do i force the image to take up the entire width of the pdf file?
alt text http://img52.imageshack.us/img52/3324/fullscreencapture121420u.png
The ScalePercent method works pretty well for this.
Dim pgSize As New iTextSharp.text.Rectangle(595, 792) //A4 width, Letter height
Dim leftMargin as integer = 20
Dim rightMargin as integer = 20
Dim doc As New iTextSharp.text.Document(pgSize, leftMargin, rightMargin, 48, 24)
//Create PDF and write other stuff.
Dim img As System.Drawing.Image = My.Resources.My_Image
Dim png As System.Drawing.Imaging.ImageFormat = System.Drawing.Imaging.ImageFormat.Png
Dim pic1 As iTextSharp.text.Image = iTextSharp.text.Image.GetInstance(img, png)
Dim scaleFactor As Single = (pgSize.Width - leftMargin - rightMargin) / img.Width * 100
pic1.ScalePercent(scaleFactor)
pic1.SetAbsolutePosition(my_X, my_Y)
doc.Add(pic1)