The cropping area has an x and y offset in the new bitmap, but only if the original has been scaled - vb.net

a strange phenomenon occurs.
With my edge detection program, I can transfer the inside of the GraphicsPath to a new image.
It always works great – except when I scale the original image with GIMP and Word (aspect ratio remains, only the dimensions are changed). Then the area is shifted. To the left and up. See attachement. In line 68, I looked what is in rectCutout. Everything OK.
Does this have anything to do with GIMP? The dots per inch are the same (72). The compression quality of the JPEG also (100%).
I just realized: if I scale an image larger, the result is completely black.
The strange thing is: I'm not saying: the picture that is drawn on is larger than the picture that is saved. Then it would be logical that the path is not in the same position. It's about the fact that the loaded image is just smaller.
I would be happy if someone could tell me why. 😄
this is the scaled image which is loaded
Here you see the GUI, ready to save
cropped image, area has x and y offset
#Disable Warning CA1707 ' Bezeichner dürfen keine Unterstriche enthalten
Imports System.Drawing.Drawing2D
Imports Microsoft.WindowsAPICodePack.Dialogs
Public NotInheritable Class AllesGrafische
Public Shared Sub Paint_the_Rectangle(ByVal g As Graphics, ByVal recta As Rectangle)
If g IsNot Nothing Then
g.SmoothingMode = SmoothingMode.AntiAlias
g.CompositingQuality = CompositingQuality.HighQuality
g.PixelOffsetMode = PixelOffsetMode.HighQuality
g.InterpolationMode = InterpolationMode.HighQualityBilinear
Using Pen_Hellblau As Pen = New Pen(Color.FromArgb(0, 200, 255), 1.0F)
g.DrawRectangle(Pen_Hellblau, recta)
End Using
End If
End Sub
Public Shared Sub Draw_Curve(ByVal g As Graphics, ByVal theList As List(Of Point))
If theList IsNot Nothing AndAlso theList.Count > 0 AndAlso g IsNot Nothing Then
g.SmoothingMode = SmoothingMode.AntiAlias
g.CompositingQuality = CompositingQuality.HighQuality
g.PixelOffsetMode = PixelOffsetMode.HighQuality
g.InterpolationMode = InterpolationMode.HighQualityBilinear
Dim theList_neu As New List(Of Point)
Using gp As New GraphicsPath
For i As Integer = 1 To theList.Count - 1 Step 1
Dim a As Integer = theList(i).X
Dim b As Integer = theList(i).Y
Dim c As Integer = theList(i - 1).X
Dim d As Integer = theList(i - 1).Y
Dim Entfernungsbetrag As Double = Math.Sqrt(Math.Pow(a, 2) + Math.Pow(b, 2) + Math.Pow(c, 2) + Math.Pow(d, 2) - 2 * a * c - 2 * b * d)
If Entfernungsbetrag < Form1.erlaubte_Entfernung Then
theList_neu.Add(theList(i))
End If
Next
If theList_neu.Count = 0 Then Return
gp.AddLines(theList_neu.ToArray())
Using Pen_hellrosa As Pen = New Pen(Color.FromArgb(255, 64, 239), 1.0F)
g.DrawPath(Pen_hellrosa, gp)
End Using
If Form1.ClosePath Then
gp.CloseFigure()
End If
If Form1.CheckBox1.Checked Then
Dim Speicherpfad As String
Using SFD1 As New CommonSaveFileDialog
SFD1.Title = "Wo soll das Bild gespeichert werden?"
SFD1.Filters.Add(New CommonFileDialogFilter("PNG", ".png"))
If System.IO.Directory.Exists("C:\Users\...\source\repos\VB.NET\Get mouse position and draw rectangle on screen") Then
SFD1.InitialDirectory = "C:\Users\...\source\repos\VB.NET\Get mouse position and draw rectangle on screen"
Else
SFD1.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.Desktop)
End If
If SFD1.ShowDialog = CommonFileDialogResult.Ok Then
Speicherpfad = SFD1.FileName & ".png"
Else
Return
End If
End Using
Using bmpSource As Bitmap = New Bitmap(Form1.Pfad_Bild)
Dim rectCutout As RectangleF = gp.GetBounds()
Using m As Matrix = New Matrix()
m.Translate(-rectCutout.Left, -rectCutout.Top)
gp.Transform(m)
End Using
Using bmpCutout As Bitmap = New Bitmap(CInt(Math.Round(rectCutout.Width, 0)), CInt(Math.Round(rectCutout.Height, 0)))
Using graphicsCutout As Graphics = Graphics.FromImage(bmpCutout)
graphicsCutout.Clip = New Region(gp)
graphicsCutout.DrawImage(bmpSource, CInt(-rectCutout.Left), CInt(-rectCutout.Top))
bmpCutout.Save(Speicherpfad, Imaging.ImageFormat.Png)
Form1.CheckBox1.Checked = False
End Using
End Using
End Using
End If
End Using
End If
End Sub
End Class
#Enable Warning CA1707 ' Bezeichner dürfen keine Unterstriche enthalten

The solution is to use .SetResolution()
Using Original As Bitmap = New Bitmap(Form1.Pfad_Bild)
Dim rectCutout As RectangleF = gp.GetBounds()
Using m As System.Drawing.Drawing2D.Matrix = New System.Drawing.Drawing2D.Matrix()
m.Translate(-rectCutout.Left, -rectCutout.Top)
gp.Transform(m)
End Using
Using bmpCutout As Bitmap = New Bitmap(CInt(Math.Round(rectCutout.Width, 0)), CInt(Math.Round(rectCutout.Height, 0)))
bmpCutout.SetResolution(Original.HorizontalResolution, Original.VerticalResolution)
.
.
.
.
.

Related

How to flip a User Control added in a picturebox by 180 degrees?

I'm adding a control to a picturebox. This control is a component, precisely it's a toggle switch posted here. I'd like this control to be vertical and not horizontal .
So, since objects can't be rotated or flipped, I found a way to flip the picturebox image with:
PictureBox1.Image.RotateFlip(RotateFlipType.Rotate180FlipNone)
PictureBox1.Refresh()
The error I'm getting at RunTime is:
System.Windows.Forms.PictureBox.Image.get returned Nothing
Endeed the control is not an image so is there a way to flip the control inside of the picturebox by 180 degrees?
Also, You think there is a way to know when the value of the toggle switch is on or off?
Thanks
As already mentioned above, extend the control to have it drawn either horizontally or vertically.
Imports System.Drawing
Imports System.Drawing.Drawing2D
Imports System.Windows.Forms
Public Class ToggleSwitch
Inherits CheckBox
Public Sub New()
MyBase.New
SetStyle(ControlStyles.AllPaintingInWmPaint Or
ControlStyles.UserPaint, True)
UpdateStyles()
Padding = New Padding(6)
End Sub
Private _orientation As Orientation = Orientation.Horizontal
Public Property Orientation As Orientation
Get
Return _orientation
End Get
Set(value As Orientation)
_orientation = value
Dim max = Math.Max(Width, Height)
Dim min = Math.Min(Width, Height)
If value = Orientation.Vertical Then
Size = New Size(min, max)
Else
Size = New Size(max, min)
End If
End Set
End Property
'Fix by: #41686d6564
<Browsable(False),
Bindable(False),
DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden),
EditorBrowsable(EditorBrowsableState.Never)>
Public Overrides Property AutoSize As Boolean
Get
Return False
End Get
Set(value As Boolean)
End Set
End Property
Protected Overrides Sub OnPaint(e As PaintEventArgs)
Dim g = e.Graphics
g.Clear(BackColor)
g.SmoothingMode = SmoothingMode.AntiAlias
g.PixelOffsetMode = PixelOffsetMode.Half
Dim p = Padding.All
Dim r = 0
Dim rec As Rectangle
Using gp = New GraphicsPath
If _orientation = Orientation.Vertical Then
r = Width - 2 * p
gp.AddArc(p, p, r, r, -180, 180)
gp.AddArc(p, Height - r - p, r, r, 0, 180)
r = Width - 1
rec = New Rectangle(0, If(Checked, Height - r - 1, 0), r, r)
'Or
'rec = New Rectangle(0, If(Checked, 0, Height - r - 1), r, r)
'To get the ON on top.
Else
r = Height - 2 * p
gp.AddArc(p, p, r, r, 90, 180)
gp.AddArc(Width - r - p, p, r, r, -90, 180)
r = Height - 1
rec = New Rectangle(If(Checked, Width - r - 1, 0), 0, r, r)
End If
gp.CloseFigure()
g.FillPath(If(Checked, Brushes.DarkGray, Brushes.LightGray), gp)
g.FillEllipse(If(Checked, Brushes.Green, Brushes.WhiteSmoke), rec)
End Using
End Sub
End Class
As for the second part of your question, please read CheckBox.Checked property and CheckBox.CheckedChanged event.
Impelemntation example:
Private Sub ToggleSwitch1_CheckedChanged(sender As Object, e As EventArgs) Handles ToggleSwitch1.CheckedChanged
If ToggleSwitch1.Checked Then
'ToDo with ON state...
Else
'ToDo with OFF state..
End If
End Sub

Redraw Picturebox at offset and back to simulate as a button effect

I have some images of document and book covers and those are displayed using pictureboxes in a Table layout panel.
Image excerpt from winform app
I am following this code
(From: https://social.msdn.microsoft.com/Forums/vstudio/en-US/da545e8e-e059-4681-9893-6d5dbdf6eba6/drop-shadow-around-the-image-in-picturebox?forum=vbgeneral)
to make picturebox work as a button when clicked and open the desired book or document.
Public Enum ShadowPosition As Integer
TopLeft = 0
TopRight = 1
BottomLeft = 2
BottomRight = 3
End Enum
Private Sub AddImageWithShadow(ByVal img As System.Drawing.Image, ByVal area As ShadowPosition, ByVal thickness As Integer, ByVal clr As Color, ByVal PicBox As PictureBox)
Using bm As New Bitmap(img.Width + thickness, img.Height + thickness)
Using gr As Graphics = Graphics.FromImage(bm)
Dim ix, iy As Integer
Dim rect As New Rectangle(thickness, thickness, img.Width, img.Height)
If area = ShadowPosition.TopLeft Or area = ShadowPosition.TopRight Then
iy = thickness
rect.Y = 0
End If
If area = ShadowPosition.TopLeft Or area = ShadowPosition.BottomLeft Then
ix = thickness
rect.X = 0
End If
gr.FillRectangle(New SolidBrush(clr), rect)
gr.DrawImage(img, ix, iy)
End Using
If PicBox.Image IsNot Nothing Then PicBox.Image.Dispose()
PicBox.Image = New Bitmap(bm)
End Using
End Sub
I tried to change the position of image:
Picturebox1.Location = New Point(10, 10)
Is there a way someone could guess to redarw picturebox at some offset without its drop shadow and back to initial state.

How to get rid of pixelated edges of a jpg?

For my student project, I’ve a vb.net code snippet that downloads a jpg file from a website and then sets all its pixels, which are almost white, entirely white:
Dim oColor As Color
Dim bRed As Byte
Dim bGreen As Byte
Dim bBlue As Byte
Dim imgTemp As Image = Image.FromFile("C:\DownloadedImage.jpg")
Dim bmpTemp As New Bitmap(imgTemp.Width, imgTemp.Height, Imaging.PixelFormat.Format32bppArgb)
Using gfx As Graphics = Graphics.FromImage(bmpTemp)
gfx.SmoothingMode = Drawing2D.SmoothingMode.AntiAlias
gfx.CompositingQuality = Drawing2D.CompositingQuality.HighQuality
gfx.InterpolationMode = Drawing2D.InterpolationMode.HighQualityBicubic
gfx.PixelOffsetMode = Drawing2D.PixelOffsetMode.HighQuality
gfx.DrawImage(imgTemp, 0, 0)
End Using
For x = 0 To bmpTemp.Width - 1
For y = 0 To bmpTemp.Height - 1
oColor = bmpTemp.GetPixel(x, y)
bRed = oColor.R
bGreen = oColor.G
bBlue = oColor.B
If bRed <= 254 AndAlso bRed >= 254 - 20 Then '20 = White Tolerance'
bmpTemp.SetPixel(x, y, Color.White)
End If
If bGreen <= 254 AndAlso bGreen >= 254 - 20 Then
bmpTemp.SetPixel(x, y, Color.White)
End If
If bBlue <= 254 AndAlso bBlue >= 254 - 20 Then
bmpTemp.SetPixel(x, y, Color.White)
End If
Next
Next
Dim newForm As New Form With {.BackgroundImage = bmpTemp, .TransparencyKey = Color.White, .BackgroundImageLayout = ImageLayout.Zoom, .BackColor = Color.White}
newForm.Show()
The bitmap created in this way is then set as the BackgroundImage of a form whose TransparencyKey property is white. The result is not a complete failure, but the edges of the isolated object are still white and pixelated:
The result in two different sizes (left) and what I'm trying to achieve (right)
I’m now looking for a way to get rid of those ragged edges, something like Photoshop’s “Refine Edge” function.
Many thanks in advance!

Changing the area of a pixel search

I have been working on an app to search for 3 pixels in a certain area then play a sound. It currently works however I wish to reduce the zone of which it searches from the whole screen to a rectangular area on my screen, this is to save memory usage of the app, here's the code that works
Private Sub dcdTimer_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles dcdTimer.Tick
Dim screensize As Size = New Size(My.Computer.Screen.Bounds.Width, My.Computer.Screen.Bounds.Height)
Dim screenshot As New Bitmap(My.Computer.Screen.Bounds.Width, My.Computer.Screen.Bounds.Height)
Dim ge As System.Drawing.Graphics = System.Drawing.Graphics.FromImage(screenshot)
Dim pointx As Integer = 1
Dim pointy As Integer = 1
ge.CopyFromScreen(New Point(0, 0), New Point(0, 0), screensize)
looking = True
Try
While looking = True
Dim atpoint As Color = screenshot.GetPixel(pointx, pointy)
Dim reckcol1 As Color = Color.FromArgb(a, r, g, b) 'first pixel colour
Dim reckcol2 As Color = Color.FromArgb(a1, r1, g1, b1) 'second pixel colour
Dim reckcol3 As Color = Color.FromArgb(a2, r2, g2, b2) 'third pixel colour
If atpoint = reckcol1 Then 'Matches 3 pixels
Dim testPoint As Color = screenshot.GetPixel(pointx, pointy + 10)
If testPoint = reckcol2 Then
Dim testPoint2 As Color = screenshot.GetPixel(pointx + 10, pointy + 10)
If testPoint2 = reckcol3 Then
My.Computer.Audio.Play(sounddir + "Found.wav")
looking = False
Sleep(15000)
pointx = 0
pointy = 0
End If
End If
End If
pointy = pointy + 1
If pointy = My.Computer.Screen.Bounds.Height Then
pointy = 0
pointx = pointx + 1
End If
End While
Catch ex As Exception
End Try
End Sub
I tried to use this code as suggested:
Dim pointofY As New Point(500, 400)
Dim screensize As New Size(400, 200)
Dim screenshot As New Rectangle(pointofY, screensize)
Dim ge As System.Drawing.Graphics = System.Drawing.Graphics.FromImage(screenshot)
However, using a rectangle does not allow me to use getpixel or use ge.copyfromscreen

Obtaing the ROI in Visual basic errors in code after conversion from C

I've been working on obtaining the ROI of an image, I'm trying to get a square shaped box that will hoover around the region an be able to click and get the standard deviation. I'm familiar with c so i used the c to VB converter, but im getting errors that the statement is not valid in namespace. Everything seems to compatible to VB code. I will be grateful for any suggestions on this matter. Thanks
Private Function DrawRoi(Image As Bitmap, rect As RectangleF) As oid
Dim roi As New Rectangle()
roi.X = CInt(CSng(Image.Width) * rect.X)
roi.Y = CInt(CSng(Image.Height) * rect.Y)
roi.Width = CInt(CSng(Image.Width) * rect.Width)
roi.Height = CInt(CSng(Image.Height) * rect.Height)
Dim timer As New Stopwatch()
timer.Start()
' graphics manipulation takes about 240ms on 1080p image
Using roiMaskImage As Bitmap = CreateRoiMaskImage(ImageWithRoi.Width, ImageWithRoi.Height, roi)
Using g As Graphics = Graphics.FromImage(ImageWithRoi)
g.DrawImage(Image, 0, 0)
g.DrawImage(roiMaskImage, 0, 0)
Dim borderPen As Pen = CreateRoiBorderPen(ImageWithRoi)
g.DrawRectangle(borderPen, roi)
End Using
End Using
Debug.WriteLine("roi graphics: {0}ms", timer.ElapsedMilliseconds)
Me.imagePictureBox.Image = ImageWithRoi
End Function
Private Function CreateRoiMaskImage(width As Integer, height As Integer, roi As Rectangle) As Bitmap
Dim image As New Bitmap(width, height, PixelFormat.Format32bppArgb)
Using g As Graphics = Graphics.FromImage(image)
Dim dimBrush As New SolidBrush(Color.FromArgb(64, 0, 0, 0))
g.FillRectangle(dimBrush, 0, 0, width, height)
Dim roiBrush As New SolidBrush(Color.Red)
g.FillRectangle(roiBrush, roi)
image.MakeTransparent(Color.Red)
Return image
End Using
End Function