Text Overlay On a Video (VB.net) - vb.net

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

Related

How to limit photo viewer to only display image files in the array?

array of the picture
Dim PicsBMP As New List(Of PictureBox)
For i As Integer = 0 To similarImageNewList.Count - 1
Pics.Add(New PictureBox)
Pics(i).Tag = i
Pics(i).Image = Image.FromFile(similarImageNewList(i))
Pics(i).Top = 25
Pics(i).Left = (i * 250) + 20
Pics(i).Width = 200
Pics(i).Height = 200
Pics(i).BorderStyle = BorderStyle.FixedSingle
Pics(i).SizeMode = PictureBoxSizeMode.StretchImage
AddHandler Pics(i).MouseClick, AddressOf imageCapture_mouseDoubleClick
Panel1.Controls.Add(Pics(i))
Next
mousedoubleClick
Private Sub imageCapture_mouseDoubleClick(ByVal sender As System.Object, ByVal e As System.EventArgs)
Dim Pics As PictureBox = DirectCast(sender, PictureBox)
Dim selected As Integer = DirectCast(Pics.Tag, Integer)
Dim filename As String = similarImageNewList(selected)
Try
Process.Start(filename)
Catch ex As Exception
MessageBox.Show("Error opening image file.",
"Load Watch Image Error",
MessageBoxButtons.OK,
MessageBoxIcon.Exclamation,
MessageBoxDefaultButton.Button1)
End Try
End Sub
array of the selected picture
Dim imagePathName As String = imageName(count).Substring(0, imageName(count).Length - 6)
Dim fileEntries As String() = Directory.GetFiles(getDirectory, imagePathName + "*.jpg")
Dim fileName As String
For Each fileName In fileEntries
If (System.IO.File.Exists(fileName)) Then
similarImageNewList.Add(fileName)
End If
Next
When the Process.Start(filename) is triggered, the windows photo viewer will be displaying all of the file images in the file.. I only want the photo viewer to be displaying the photos included in the similarImageNewList.(i) loop..

VB.NET resize and crop images

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

how to add custom header to datagridview print with visual basic

I was able to print a data on a datagridview, and it prints without problem. now, i wanted to add a header text or image to the print out of the datagridview. i couldn't figure out how to do that. i have attached the code used to print the datagridview.
Private bitmap As Bitmap
Private Sub btnprintreport_Click(sender As Object, e As EventArgs) Handles btnprintreport.Click
Try
Dim height As Integer = reportsellinggridview.Height
reportsellinggridview.Height = reportsellinggridview.RowCount * reportsellinggridview.RowTemplate.Height
'Create a Bitmap and draw the DataGridView on it.
bitmap = New Bitmap(Me.reportsellinggridview.Width, Me.reportsellinggridview.Height)
reportsellinggridview.DrawToBitmap(bitmap, New Rectangle(0, 0, Me.reportsellinggridview.Width, Me.reportsellinggridview.Height))
'Resize DataGridView back to original height.
reportsellinggridview.Height = height
PrintDocument1.DefaultPageSettings.Landscape = True
'Show the Print Preview Dialog.
PrintPreviewDialog1.Document = PrintDocument1
PrintPreviewDialog1.PrintPreviewControl.Zoom = 1
PrintPreviewDialog1.ShowDialog()
Catch ex As Exception
MessageBox.Show("Could not print, please turn on the printer and make sure it is set as default printer", "print error", MessageBoxButtons.OK, MessageBoxIcon.Error)
End Try
End Sub
Private Sub PrintPage(sender As Object, e As System.Drawing.Printing.PrintPageEventArgs) Handles PrintDocument1.PrintPage
'Print the contents.
e.Graphics.DrawImage(bitmap, 0, 0)
End Sub

vb.net 2010 PrintDocument Margins not working even if I set the margins

I am reading from a text file and then printing the string using printdocument via vb.net 2010.
Here is my code :
Public Class myPrinter
Friend TextToBePrinted As String
Public Sub prt(ByVal text As String)
Dim psize As New System.Drawing.Printing.PaperSize("Custom Paper Size", 850, 550)
Dim newMargins As New System.Drawing.Printing.Margins(0, 0, 0, 0)
TextToBePrinted = text
Dim prn As New Printing.PrintDocument
Using (prn)
prn.PrinterSettings.PrinterName = frmStockOut.printer
prn.PrinterSettings.Copies = frmStockOut.copies
prn.PrinterSettings.DefaultPageSettings.PaperSize = psize
prn.PrinterSettings.DefaultPageSettings.Margins = newMargins
prn.DefaultPageSettings.PaperSize = psize
prn.DefaultPageSettings.Margins = newMargins
AddHandler prn.PrintPage, _
AddressOf Me.PrintPageHandler
prn.Print()
RemoveHandler prn.PrintPage, _
AddressOf Me.PrintPageHandler
End Using
End Sub
Private Sub PrintPageHandler(ByVal sender As Object, _
ByVal args As Printing.PrintPageEventArgs)
Dim myFont As New Font("Courier New", 11)
args.Graphics.DrawString(TextToBePrinted, _
New Font(myFont, FontStyle.Regular), _
Brushes.Black, 50, 50)
End Sub
End Class
Private Sub PrintDocument1_PrintPage(ByVal sender As Object, ByVal e As System.Drawing.Printing.PrintPageEventArgs) Handles PrintDocument1.PrintPage
Dim charactersOnPage As Integer = 0
Dim linesPerPage As Integer = 0
' Sets the value of charactersOnPage to the number of characters
' of stringToPrint that will fit within the bounds of the page.
e.Graphics.MeasureString(stringToPrint, Me.Font, e.MarginBounds.Size, _
StringFormat.GenericTypographic, charactersOnPage, linesPerPage)
' Draws the string within the bounds of the page
e.Graphics.DrawString(stringToPrint, Me.Font, Brushes.Black, _
e.MarginBounds, StringFormat.GenericTypographic)
' Remove the portion of the string that has been printed.
stringToPrint = stringToPrint.Substring(charactersOnPage)
' Check to see if more pages are to be printed.
e.HasMorePages = stringToPrint.Length > 0
End Sub
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
ReadFile() ' will read text file and store in a string
Dim Print As New myPrinter
Dim myprintdialog As New PrintDialog
With myprintdialog
If .ShowDialog = Windows.Forms.DialogResult.OK Then
printer = .PrinterSettings.PrinterName
copies = .PrinterSettings.Copies
Print.prt(stringToPrint)
End If
End With
End Sub
The problem is even after I set the left margin and top margin to 0, it seems nothing has changed, it is still printing almost 3/4 inch for top margins and 1 inch for the left margin. This is also the output when I didn't set the margins. However, when I prn.OriginAtMargins = True , the output becomes a little different, left margin is now almost 1/2 inch but top margin remains the same. Something wrong with my code?
What I want to accomplish is the top margin can be set at approximately 20 pixels (assuming 100 pixels is equal to 1 inch) and left margin be set at 20 pixels too. Hope somebody can help me.

How to crop an image in vb.net?

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