The image can be anything. It can be jpg, png, anything.
Load it.
Crop it. Say removing first 100 pixels from the left.
Save to the same file
Use Graphics.DrawImage Method (Image, RectangleF, RectangleF, GraphicsUnit) method.
Dim fileName = "C:\file.jpg"
Dim CropRect As New Rectangle(100, 0, 100, 100)
Dim OriginalImage = Image.FromFile(fileName)
Dim CropImage = New Bitmap(CropRect.Width, CropRect.Height)
Using grp = Graphics.FromImage(CropImage)
grp.DrawImage(OriginalImage, New Rectangle(0, 0, CropRect.Width, CropRect.Height), CropRect, GraphicsUnit.Pixel)
OriginalImage.Dispose()
CropImage.Save(fileName)
End Using
Ref: Graphics.DrawImage and Image Cropping with Image Resizing Using VB.NET
private void btnCropImage_Click(object sender, EventArgs e)
{
OpenFileDialog dlg = new OpenFileDialog();
dlg.ShowDialog();
//check your filename or set constraint on fileopen dialog
//to open image files
string str = dlg.FileName;
//Load Image File to Image Class Object to make crop operation
Image img = System.Drawing.Bitmap.FromFile(str);
// Create rectangle for source image, what ever it's size.
GraphicsUnit units = GraphicsUnit.Pixel;
RectangleF srcRect = img.GetBounds(ref units);
// Create rectangle for displaying image - leaving 100 pixels from left saving image size.
RectangleF destRect = new RectangleF(100.0F, 0.0F, srcRect.Width - 100, srcRect.Height);
// Bitmap class object to which saves croped image
Bitmap bmp = new Bitmap((int)srcRect.Width - 100, (int)srcRect.Height);
// Draw image to screen.
Graphics grp = Graphics.FromImage(bmp);
grp.DrawImage(img, destRect, srcRect, units);
//save image to disk
bmp.Save("e:\\img.jpeg", System.Drawing.Imaging.ImageFormat.Jpeg);
//Clear memory for Unused Source Image
img.Dispose();
}
Hope this help you..
Region "Image Cropping"
Dim cropX As Integer
Dim cropY As Integer
Dim cropWidth As Integer
Dim cropHeight As Integer
Dim oCropX As Integer
Dim oCropY As Integer
Dim cropBitmap As Bitmap
Public cropPen As Pen
Public cropPenSize As Integer = 1 '2
Public cropDashStyle As Drawing2D.DashStyle = Drawing2D.DashStyle.Solid
Public cropPenColor As Color = Color.Yellow
Private Sub RotateBtn_Click(sender As System.Object, e As EventArgs) Handles RotateBtn.Click
' RotateImage(PreviewPictureBox.Image, offset:=, angle:=90)
crobPictureBox.Image.RotateFlip(RotateFlipType.Rotate270FlipNone)
'PreviewPictureBox.Image.RotateFlip(RotateFlipType.Rotate270FlipNone)
'(45, PreviewPictureBox.Image)
End Sub
Private Sub crobPictureBox_MouseDown(ByVal sender As System.Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles crobPictureBox.MouseDown
Try
If e.Button = Windows.Forms.MouseButtons.Left Then
cropX = e.X
cropY = e.Y
cropPen = New Pen(cropPenColor, cropPenSize)
cropPen.DashStyle = DashStyle.DashDotDot
Cursor = Cursors.Cross
End If
crobPictureBox.Refresh()
Catch exc As Exception
End Try
End Sub
Dim tmppoint As Point
Private Sub crobPictureBox_MouseMove(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles crobPictureBox.MouseMove
Try
If crobPictureBox.Image Is Nothing Then Exit Sub
If e.Button = Windows.Forms.MouseButtons.Left Then
crobPictureBox.Refresh()
cropWidth = e.X - cropX
cropHeight = e.Y - cropY
crobPictureBox.CreateGraphics.DrawRectangle(cropPen, cropX, cropY, cropWidth, cropHeight)
End If
' GC.Collect()
Catch exc As Exception
If Err.Number = 5 Then Exit Sub
End Try
End Sub
Private Sub crobPictureBox_MouseUp(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles crobPictureBox.MouseUp
Try
Cursor = Cursors.Default
Try
If cropWidth < 1 Then
Exit Sub
End If
Dim rect As Rectangle = New Rectangle(cropX, cropY, cropWidth, cropHeight)
Dim bit As Bitmap = New Bitmap(crobPictureBox.Image, crobPictureBox.Width, crobPictureBox.Height)
cropBitmap = New Bitmap(cropWidth, cropHeight)
Dim g As Graphics = Graphics.FromImage(cropBitmap)
g.InterpolationMode = Drawing2D.InterpolationMode.HighQualityBicubic
g.PixelOffsetMode = Drawing2D.PixelOffsetMode.HighQuality
g.CompositingQuality = Drawing2D.CompositingQuality.HighQuality
g.DrawImage(bit, 0, 0, rect, GraphicsUnit.Pixel)
' g.DrawImage(bit, 0, 0, rect,GraphicsUnit.Pixel)
PreviewPictureBox.Image = cropBitmap
Catch exc As Exception
End Try
Catch exc As Exception
End Try
End Sub
Related
I am still unable to find this solutions, could you please help me that would be great for me. Actually I want to load picture into Flowlayoutpanel without Openfiledialog, whenever I want to run the application it automatically load picture from given file path.
Private Sub Form1_Activated(sender As Object, e As EventArgs) Handles Me.Activated
Dim TheFilePath As String
Dim F as string = System.IO.Directory.GetFiles(Application.StartupPath + "C:\Users\Mohammed Waseem\Pictures\", "*.jpg")
Dim fbd As New FolderBrowserDialog
If fbd.ShowDialog = Windows.Forms.DialogResult.OK Then
TheFilePath = fbd.SelectedPath
Try
For Each F As String In System.IO.Directory.GetFiles(fbd.SelectedPath)
Dim NewImage As Image = Image.FromFile(F)
NewImage = NewImage.GetThumbnailImage(NewImage.Width * 0.5, NewImage.Height * 0.5, AddressOf abort, System.IntPtr.Zero)
Dim P As New PictureBox
P.SizeMode = PictureBoxSizeMode.AutoSize
P.Image = NewImage
AddHandler P.Click, AddressOf PictureBox1_Click
FlowLayoutPanel1.Controls.Add(P)
ListBox1.Items.Add(System.IO.Path.GetFileName(F))
Next
Catch ex As Exception
End Try
End If
End Sub
Private Function abort() As Boolean
Return False
End Function
Private Sub PictureBox1_Click(sender As Object, e As EventArgs) Handles PictureBox1.Click
Dim strFileName As String = DirectCast(sender, PictureBox).Tag.ToString
MsgBox(strFileName.ToString)
Process.Start(strFileName)
End Sub
Here's an example using your hard-coded folder:
Dim ImageExtension As String = "*.jpg"
Dim FolderPath As String = "C:\Users\Mohammed Waseem\Pictures\"
For Each FilePath As String In System.IO.Directory.GetFiles(FolderPath, ImageExtension)
Try
Dim NewImage As Image = Image.FromFile(FilePath)
NewImage = NewImage.GetThumbnailImage(NewImage.Width * 0.5, NewImage.Height * 0.5, AddressOf abort, System.IntPtr.Zero)
Dim P As New PictureBox
P.SizeMode = PictureBoxSizeMode.AutoSize
P.Image = NewImage
AddHandler P.Click, AddressOf PictureBox1_Click
FlowLayoutPanel1.Controls.Add(P)
ListBox1.Items.Add(System.IO.Path.GetFileName(FilePath))
Catch ex As Exception
End Try
Next
I am trying to write (type) directly onto a bitmap. I need to be able to type at the mouse position, so where ever on the screen i click the mouse, I can start typing text with the keyboard.
Here is a working VS 2017 VB Win Form code that will print "Hello World" at the mousedown position. But it only works with predetermined text. I would like to be able to just type at that spot. I feel I am so close, just can't get it to work.
Imports System.IO
Imports System.Windows.Forms.DataVisualization.Charting
Public Class Form1
Dim WithEvents Chart1 As New Chart
Private Structure TextPoints
Dim MPos As Point
Dim Txt As String
End Structure
Private TextList As New List(Of TextPoints)
Private TempPoint As Point
Private FirstPoint As Point
Dim xcnt As Integer = -1
Dim ycnt As Integer = -1
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles Me.Load
Me.Size = New Size(1100, 700)
Me.Location = New Point(10, 10)
MakeBackImage()
With Chart1
.Name = "Chart1"
.Location = New System.Drawing.Point(40, 40)
.Size = New System.Drawing.Size(1010, 610)
.BackImage = "BackImg.jpg"
.Parent = Me
End With
End Sub
Private Sub Chart1_MouseDown(ByVal sender As Object,
ByVal e As System.Windows.Forms.MouseEventArgs) _
Handles Chart1.MouseDown
FirstPoint = New Point(e.X, e.Y)
TempPoint = New Point(e.X, e.Y)
Me.Refresh()
End Sub
Private Sub Chart1_MouseUp(ByVal sender As Object,
ByVal e As System.Windows.Forms.MouseEventArgs) _
Handles Chart1.MouseUp
Dim T As New TextPoints With {
.MPos = TempPoint,
.Txt = "Hello World"}
TextList.Add(T)
Me.Refresh()
End Sub
Private Sub MakeBackImage()
Dim x, y As Integer
Dim img As Image = New Bitmap(1020, 620)
Dim graphics As Graphics = Graphics.FromImage(img)
graphics.Clear(Drawing.Color.White)
For x = 0 To 1000 Step 20
graphics.DrawLine(Pens.Black, x, 0, x, 600)
xcnt += 1
Next
For y = 0 To 600 Step 20
ycnt += 1
graphics.DrawLine(Pens.Black, 0, y, 1000, y)
Next
img.Save("BackImg.jpg", Imaging.ImageFormat.Jpeg)
End Sub
Private Sub Chart1_Paint(ByVal sender As Object,
ByVal e As System.Windows.Forms.PaintEventArgs) _
Handles Chart1.Paint
Dim drawString As String = "Hello World"
Dim drawFont As New Font("Arial", 14)
Dim drawBrush As New SolidBrush(Color.Black)
For Each t As TextPoints In TextList
e.Graphics.DrawString(t.Txt, drawFont,
drawBrush, t.MPos.X, t.MPos.Y)
Next
End Sub
End Class
This is a simplified code. Actually, the background image is only created once, but I added code to dynamically create it here to make the demo better.
You may have seen this question on other forum but i still can't resolve this issue.
I manage to get the text overlay for few second but after that it disappears and display following image (it does not stop the program):
i have a code like this when i got above error:
Private Sub CAPTURAR(sender As Object, eventArgs As NewFrameEventArgs)
If ButtonVIDEO.BackColor = Color.Black Then 'if n ot recording......
BMP = DirectCast(eventArgs.Frame.Clone(), Bitmap) 'PONE LOS DATOS EN EL BITMAP
PictureBox1.Image = DirectCast(eventArgs.Frame.Clone(), Bitmap) 'PUT THE DATA IN THE BITMAP
BMP.Dispose()
'insert text overlay
If BMP IsNot Nothing Then
Dim g As Graphics = Graphics.FromImage(PictureBox1.Image)
g.DrawString(New String("new"), New Font("Arial", 16), Brushes.White, New Rectangle(10, 10, 200, 50))
g.Dispose()
End If
Else ' SI ESTAS GRABANDO...
BMP = DirectCast(eventArgs.Frame.Clone(), Bitmap) ' If YOU ARE RECORDING
PictureBox1.Image = DirectCast(eventArgs.Frame.Clone(), Bitmap) 'PRESENTS THEM AT THE PICTURE BOX
ESCRITOR.WriteVideoFrame(BMP) 'KEEP THEM IN THE MEMORY
End If
End Sub
The full code is here: AForge WebCam Recorder
Thanks in advance
-
14 Jan 2020: updated code and i got the overlay on the video perfectly:
Private Sub ButtonVIDEO_Click(sender As System.Object, e As System.EventArgs) Handles ButtonVIDEO.Click
If ButtonVIDEO.BackColor = Color.Black Then 'YOU ARE NOT RECORDING VIDEO
SaveFileDialog1.DefaultExt = ".avi" 'SAVE AS AVI FILE
If SaveFileDialog1.ShowDialog() = System.Windows.Forms.DialogResult.OK Then
Dim ANCHO As Integer = CAMARA.VideoResolution.FrameSize.Width 'DEFINE THE WIDTH OF THE PHOTOGRAPH
Dim ALTO As Integer = CAMARA.VideoResolution.FrameSize.Height 'DEFINE THE HIGH OF THE PHOTOGRAPH
'CREATE THE FILE FOR DATA WITH SAVED PARAMETERS
ESCRITOR.Open(SaveFileDialog1.FileName, ANCHO, ALTO, NumericUpDownFPS.Value, VideoCodec.Default, NumericUpDownBRT.Value * 1000)
ESCRITOR.WriteVideoFrame(BMP) 'START SAVING DATA
ButtonVIDEO.BackColor = Color.Red 'SO WE KNOW THAT HE'S RECORDING
End If
Else
ButtonVIDEO.BackColor = Color.Black 'YOU ARE RECORDING
ESCRITOR.Close() 'STOP SAVING DATA
End If
End Sub
Private Sub CAPTURAR(ByVal sender As Object, ByVal eventArgs As NewFrameEventArgs)
Me.Invoke(CType(Function()
If ButtonVIDEO.BackColor = Color.Black Then 'IF YOU ARE NOT RECORDING ......
BMP = DirectCast(eventArgs.Frame.Clone(), Bitmap) 'PUT THE DATA IN THE BITMAP
PictureBox1.Image = DirectCast(eventArgs.Frame.Clone(), Bitmap) 'PRESENTS THEM AT THE PICTURE BOX
'insert text overlay
Else 'IF YOU ARE RECORDING ...
Try
BMP = DirectCast(eventArgs.Frame.Clone(), Bitmap) 'PUT THE DATA IN THE BITMAP
PictureBox1.Image = DirectCast(eventArgs.Frame.Clone(), Bitmap) 'PRESENTS THEM AT THE PICTURE BOX
ESCRITOR.WriteVideoFrame(BMP) 'KEEP THEM IN THE MEMORY
Catch ex As Exception
End Try
End If
If BMP IsNot Nothing Then
Dim g As Graphics = Graphics.FromImage(PictureBox1.Image)
g.DrawString(New String("new"), New Font("Arial", 16), Brushes.White, New Rectangle(10, 10, 200, 50))
g.Dispose()
End If
Me.Invoke(CType(Function()
End Function, MethodInvoker))
GC.Collect()
End Function, MethodInvoker))
End Sub
i have a VSTO for powerpoint and want to resize images so they are the same size as the slide. a sample image i have is 1000x300 and the slide is 960x540. so this is the code i have:
_W=960
_H=540
Dim img As Image = System.Drawing.Bitmap.FromFile(file1)
OldRect = New RectangleF(233, 0, 533, 300) ' calculated values to crop left and right
NewRect = New RectangleF(0, 0, _W, _H)
Dim bmp As Bitmap = New Bitmap(img, _W, _H)
Dim g As Graphics = Graphics.FromImage(bmp)
g.InterpolationMode = Drawing2D.InterpolationMode.HighQualityBicubic
g.PixelOffsetMode = Drawing2D.PixelOffsetMode.HighQuality
g.CompositingQuality = Drawing2D.CompositingQuality.HighQuality
g.DrawImage(img, NewRect, OldRect, GraphicsUnit.Pixel)
img.Save(file2, Imaging.ImageFormat.Png)
but when i look at file2 it's the same 1000x300 file as the original. what am i missing here?
#plutonix; you're spot on. i was under the wrong impression that DrawImage would replace the image it was offered. but saving the bitmap the graphics object was created with produced the intended image.
bmp.Save(file2, Imaging.ImageFormat.Png)
works perfect. thanks!
The answer posted here is good but there is one major problem of quality that need to be addressed. In most cased you have to Crop Image and Maintain the Quality so in that regard, I have improved the crop feature of a sample and posted below is the link. This demo is in VB.NET but you can easily understand the concept and make adjustments.
http://www.mediafire.com/file/70rmlpcdjyxo8gc/ImageCroppingDemo_-_Maintain_Image_Quality.zip/file
CODES For Cropping (VB.NET)
Dim cropX As Integer
Dim cropY As Integer
Dim cropWidth As Integer
Dim cropHeight As Integer
Dim oCropX As Integer
Dim oCropY As Integer
Dim cropBitmap As Bitmap
Dim Loadedimage As Image
Public cropPen As Pen
Public cropPenSize As Integer = 1 '2
Public cropDashStyle As Drawing2D.DashStyle = Drawing2D.DashStyle.Solid
Public cropPenColor As Color = Color.Yellow
Private Sub crobPictureBox_MouseDown(ByVal sender As System.Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles crobPictureBox.MouseDown
Try
If e.Button = Windows.Forms.MouseButtons.Left Then
cropX = e.X
cropY = e.Y
cropPen = New Pen(cropPenColor, cropPenSize)
cropPen.DashStyle = DashStyle.DashDotDot
Cursor = Cursors.Cross
End If
crobPictureBox.Refresh()
Catch exc As Exception
End Try
End Sub
Dim tmppoint As Point
Private Sub crobPictureBox_MouseMove(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles crobPictureBox.MouseMove
Try
If crobPictureBox.Image Is Nothing Then Exit Sub
If e.Button = Windows.Forms.MouseButtons.Left Then
crobPictureBox.Refresh()
cropWidth = e.X - cropX
cropHeight = e.Y - cropY
crobPictureBox.CreateGraphics.DrawRectangle(cropPen, cropX, cropY, cropWidth, cropHeight)
End If
' GC.Collect()
Catch exc As Exception
If Err.Number = 5 Then Exit Sub
End Try
End Sub
Private Sub crobPictureBox_MouseUp(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles crobPictureBox.MouseUp
Try
Cursor = Cursors.Default
Try
If cropWidth < 1 Then
Exit Sub
End If
Dim smallWidthPercentage As Single = (cropWidth / crobPictureBox.Width) * 100
Dim smallHeightPercentage As Single = (cropHeight / crobPictureBox.Height) * 100
Dim smallXPercentage As Single = (cropX / crobPictureBox.Width) * 100
Dim smallYPercentage As Single = (cropY / crobPictureBox.Height) * 100
smallHeightPercentage += 10
smallYPercentage -= 10
Dim Widthdifference As Integer = Loadedimage.Width - crobPictureBox.Width
Dim HeightDifference As Integer = Loadedimage.Height - crobPictureBox.Height
Dim rect As Rectangle
rect = New Rectangle((smallXPercentage / 100) * Loadedimage.Width, (smallYPercentage / 100) * Loadedimage.Height, (smallWidthPercentage / 100) * Loadedimage.Width, (smallHeightPercentage / 100) * Loadedimage.Height)
Dim bit As Bitmap = New Bitmap(Loadedimage, Loadedimage.Width, Loadedimage.Height)
cropBitmap = New Bitmap(Loadedimage, (smallWidthPercentage / 100) * Loadedimage.Width, (smallHeightPercentage / 100) * Loadedimage.Height)
Dim g As Graphics = Graphics.FromImage(cropBitmap)
g.InterpolationMode = Drawing2D.InterpolationMode.HighQualityBicubic
g.PixelOffsetMode = Drawing2D.PixelOffsetMode.HighQuality
g.CompositingQuality = Drawing2D.CompositingQuality.HighQuality
g.DrawImage(bit, 0, 0, rect, GraphicsUnit.Pixel)
PreviewPictureBox.Image = cropBitmap
Catch exc As Exception
End Try
Catch exc As Exception
End Try
End Sub
i want to maintain the location of picturebox2 which is inside a panel. in my case, the image looks like this.. https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcQ8SUu7ZXBJVXrhic-Xou9OsW4h7QDd8yH5xhYtV3DlnJ0Q1UVJiw (there's a map /picturebox1/ and the color green locator or pointer is another picturebox /picturebox2/)
is it possible to zoom in and zoom out the image without losing the right coordinates? Because i want to maintain the location of the locator(picturebox2) in the map (picturebox1)
so far, i can now zoom in and zoom out the image in the scrollable panel using trackbar. but my only problem is that, the picturebox2 (another image above the picturebox1) needs to move its location as picturebox1 is zooming.
Public ClassForm1
Private img original As Image
Private m_PanStartPoint As New Point
Private n_PanStartPoint As New Point
Private Sub Form1_Load(ByVal sender AsSystem.Object, ByVal e AsSystem.EventArgs) Handles MyBase.Load
imgoriginal = Image.FromFile("C:\New Folder\picture1.jpg")
PictureBox1.BackgroundImageLayout = ImageLayout.Stretch
zoomSlider.Minimum = 1
zoomSlider.Maximum = 5
zoomSlider.SmallChange = 1
zoomSlider.LargeChange = 1
zoomSlider.UseWaitCursor = False
Me.DoubleBuffered = True
Panel1.AutoScroll = True
PictureBox1.SizeMode = PictureBoxSizeMode.AutoSize
PictureBox1.Parent = PictureBox1
PictureBox2.Parent = PictureBox1
PictureBox1.BackColor = Color.Transparent
Dim mstream As NewSystem.IO.MemoryStream()
PictureBox1.Image = Image.FromStream(mstream)
PictureBox2.Location = NewSystem.Drawing.Point(100, 100)
End Sub
Public Function pictureboxzoom(ByValimgAsImage, ByVal size AsSize) AsImage
Dim bm As Bitmap = New Bitmap(img, Convert.ToInt32(img.Width * size.Width), Convert.ToInt32(img.Height * size.Height))
Dim grap As Graphics = Graphics.FromImage(bm)
grap.InterpolationMode = Drawing2D.InterpolationMode.HighQualityBicubic
Return bm
End Function
Private Sub zoomSlider_Scroll(ByVal sender AsSystem.Object, ByVal e AsSystem.EventArgs) Handles zoomSlider.Scroll
If zoomSlider.Value> 0 Then
PictureBox1.Image = Nothing
PictureBox1.Image = pictureboxzoom(imgoriginal, New Size(zoomSlider.Value, zoomSlider.Value))
End If
End Sub
Private Sub PictureBox1_MouseDown(ByVal sender AsObject, ByVal e AsSystem.Windows.Forms.MouseEventArgs) Handles PictureBox1.MouseDown
m_PanStartPoint = NewPoint(e.X, e.Y)
End Sub
Private Sub PictureBox1_MouseMove(ByVal sender AsObject, ByVal e As System.Windows.Forms.MouseEventArgs) Handles PictureBox1.MouseMove
If e.Button = Windows.Forms.MouseButtons.Left Then
Dim DeltaX As Integer = (m_PanStartPoint.X - e.X)
Dim DeltaY As Integer = (m_PanStartPoint.Y - e.Y)
Panel1.AutoScrollPosition = _
New Drawing.Point((DeltaX - Panel1.AutoScrollPosition.X), _
(DeltaY - Panel1.AutoScrollPosition.Y))
Button1.Location = New System.Drawing.Point(0, 0)
End If
End Sub
End Class