Restrict Image by selecting it's URL - vb.net

I am trying to add Images from websites and I am facing poblem with an issue which is that when I am trying to go to google images and trying to add some Images and when I right click for some images I find "Copy Image URL" and for some I don't find it and I find "Copy link address".Now I want my users to restrict from adding the Images which contain "Copy Image URL"
And I am attaching Images so that you'll understand me in a better way.
How do I do that?
Here is the code for saving the image:
Dim dir_name As String = txtDirectory.Text
If Not dir_name.EndsWith("\") Then dir_name &= "\"
For Each pic As PictureBox In flpPictures.Controls
Dim bm As Bitmap = CType(pic.Image, Bitmap)
Dim filename As String = CStr(pic.Tag)
filename = filename.Substring(filename.LastIndexOf("/") + 1)
Dim ext As String = filename.Substring(filename.LastIndexOf("."))
'Here it gives me an error at(filename.lastindexof(".")
Dim full_name As String = dir_name & filename
Select Case ext
Case ".bmp"
bm.Save(full_name, Imaging.ImageFormat.Bmp)
Case ".gif"
bm.Save(full_name, Imaging.ImageFormat.Gif)
Case ".jpg", "jpeg"
bm.Save(full_name, Imaging.ImageFormat.Jpeg)
Case ".png"
bm.Save(full_name, Imaging.ImageFormat.Png)
Case ".tiff"
bm.Save(full_name, Imaging.ImageFormat.Tiff)
Case Else
MessageBox.Show( _
"Unknown file type " & ext & _
" in file " & filename, _
"Unknown File Type", _
MessageBoxButtons.OK, _
MessageBoxIcon.Error)
End Select
Next pic
Beep()

'WEB CLIENT IS NEEDED TO DO THE DOWNLOAD
Dim MyWebClient As New System.Net.WebClient
'BYTE ARRAY HOLDS THE DATA
Dim ImageInBytes() As Byte = MyWebClient.DownloadData(url)
'CREATE A MEMORY STREAM USING THE BYTES
Dim ImageStream As New IO.MemoryStream(ImageInBytes)
'CREATE A BITMAP FROM THE MEMORY STREAM
PictureBox1.Image = New System.Drawing.Bitmap(ImageStream)

In the top screenshot, you are right-clicking directly on an image.
In the bottom screenshot, you are right-clicking on an empty div with a z-index that puts it above the image.
Here's an example:
<a href="http://example.com">
<img src="myImg.jpg" style="position: absolute;" />
<div style="z-index:1; position:absolute; width:100%; height:100%;"></div>
</a>
When you mouse over the link in Google Images another div is shown on top that contains the saveable image. Have a look with Firebug and see for yourself :)
Note that there is no perfect way to prevent users from saving images from your website. You can disable right click, mask the image with a div, mask the image with a transparent image (so the user can right-click and save the image but they get the wrong one), prevent caching etc but ultimately any tech savvy user can get around this. Still, these approaches will stop casual users so it's better than nothing. If you want to find out more about the methods that I just named, I suggest Googling for "disable save image as" or "disable copy image url".

maybe helpful
Sub Base64Convert(ByVal Base64MSG As String)
'Setup image and get data stream together
Dim img As System.Drawing.Image
Dim MS As System.IO.MemoryStream = New System.IO.MemoryStream
Dim b64 As String = Base64MSG
Dim b() As Byte
'Converts the base64 encoded msg to image data
b = Convert.FromBase64String(b64)
MS = New System.IO.MemoryStream(b)
'creates image
img = System.Drawing.Image.FromStream(MS)
'writes image for displaying
img.Save(Request.ServerVariables("APPL_PHYSICAL_PATH") & "LabelInfo.tiff", System.Drawing.Imaging.ImageFormat.Tiff)
'cleaning up house
img.Dispose()
MS.Close()
End Sub

Related

How can I save an image using System.Drawing.Imaging without auto rotating it?

When I resize my image and save it using the "System.Drawing.Imaging" save function, it adds the rotation embedded from the EXIF data and rotates my good original picture 180 degrees. I tried saving it in a different format to remove the EXIF data but it still includes the EXIF rotation for the new picture. Any ideas on how I can save the picture in the orientation I can see in the thumbnails .
Private Sub ClearEXIF()
Dim Pname As String = Nothing
For Each Fil In Directory.GetFiles(DlDir)
OK2Go = False
If Fil.Contains("jpg") Then OK2Go = True
If Fil.Contains("jpeg") Then OK2Go = True
If OK2Go Then
Dim bmp As Bitmap = Image.FromFile(Fil)
Pname = GetLastName(Fil) 'this function gets the name of the jpg without the path info
temp1 = Split(Pname, ".")
bmp.Save("C:\Temp\Flat\" & temp1(0) & "+" & temp1(1) & ".png", ImageFormat.png)
bmp.Dispose()
End If
Next
MsgBox("Done")
End Sub

PDF fill in not merging correctly

We are using an asp.net website with iTextSharp.dll version 5.5.13
We can merge multiple PDF files into one using a stream and it works perfectly. However, when we use a PDF that was created in a "fill-in" function the new PDF file does not correctly merge into the other documents. It merges without the filled in values. However, if I open the filled in PDF that it creates the filled in data displays and prints fine.
I have tried merging the new "filled in" PDF at a later time but it still displays the template file as though the filled in data was missing.
Below code fills in the data
Dim strFileName As String = Path.GetFileNameWithoutExtension(strSourceFile)
Dim strOutPath As String = HttpContext.Current.Server.MapPath("~/Apps/Lifetime/OfficeDocs/Export/")
newFile = strOutPath & strFileName & " " & strRONumber & ".pdf"
If Not File.Exists(newFile) Then
Dim pdfReader As PdfReader = New PdfReader(strSourceFile)
Using pdfStamper As PdfStamper = New PdfStamper(pdfReader, New FileStream(newFile, FileMode.Create))
Dim pdfFormFields As AcroFields = pdfStamper.AcroFields
pdfFormFields.SetField("CUSTOMER NAME", strCustomer)
pdfFormFields.SetField("YR MK MODEL", strVehicle)
pdfFormFields.SetField("RO#", strRONumber)
pdfStamper.FormFlattening = False
pdfStamper.Dispose()
End Using
End If
Then code below here merges multiple PDF files/paths sent to it
Public Shared Sub MergePDFs(ByVal files As List(Of String), ByVal filename As String)
'Gets a list of full path files and merges into one memory stream
'and outputs it to a browser response.
Dim MemStream As New System.IO.MemoryStream
Dim doc As New iTextSharp.text.Document
Dim reader As iTextSharp.text.pdf.PdfReader
Dim numberOfPages As Integer
Dim currentPageNumber As Integer
Dim writer As iTextSharp.text.pdf.PdfWriter = iTextSharp.text.pdf.PdfWriter.GetInstance(doc, MemStream)
doc.Open()
Dim cb As iTextSharp.text.pdf.PdfContentByte = writer.DirectContent
Dim page As iTextSharp.text.pdf.PdfImportedPage
Dim strError As String = ""
For Each strfile As String In files
reader = New iTextSharp.text.pdf.PdfReader(strfile)
numberOfPages = reader.NumberOfPages
currentPageNumber = 0
Do While (currentPageNumber < numberOfPages)
currentPageNumber += 1
doc.SetPageSize(reader.GetPageSizeWithRotation(currentPageNumber))
doc.NewPage()
page = writer.GetImportedPage(reader, currentPageNumber)
cb.AddTemplate(page, 0, 0)
Loop
Next
doc.Close()
doc.Dispose()
If MemStream Is Nothing Then
HttpContext.Current.Response.Write("No Data is available for output")
Else
HttpContext.Current.Response.Clear()
HttpContext.Current.Response.ContentType = "application/pdf"
HttpContext.Current.Response.AppendHeader("Content-Disposition", "inline; filename=" + filename)
HttpContext.Current.Response.BinaryWrite(MemStream.ToArray)
HttpContext.Current.Response.OutputStream.Flush()
HttpContext.Current.Response.OutputStream.Close()
HttpContext.Current.Response.OutputStream.Dispose()
MemStream.Close()
MemStream.Dispose()
End If
End Sub
I expect the "filled in" PDF in the list of files to retain the filled in data but it does not. Even if I try to merge the filled in file later it still comes up missing the filled in data. If I print the filled in file it looks perfect.
PdfWriter.GetImportedPage only returns you a copy of the page contents. This does not include any annotations, in particular not the widget annotations of form fields on the page at hand.
To also copy the annotations of the source pages, use the iText PdfCopy class instead. This class is designed to copy pages including all annotations. Furthermore, it includes methods to copy all pages of a source document in one step.
You have to tell the PdfCopy object to merge fields, otherwise the document-wide form structure won't be built.
As an aside, your code creates many PdfReader objects but does not close them. That may increase your memory requirements substantially.
Thus:
Public Shared Sub MergePDFsImproved(ByVal files As List(Of String), ByVal filename As String)
Using mem As New MemoryStream()
Dim readers As New List(Of PdfReader)
Using doc As New Document
Dim copy As New PdfCopy(doc, mem)
copy.SetMergeFields()
doc.Open()
For Each strfile As String In files
Dim reader As New PdfReader(strfile)
copy.AddDocument(reader)
readers.Add(reader)
Next
End Using
For Each reader As PdfReader In readers
reader.Close()
Next
HttpContext.Current.Response.Clear()
HttpContext.Current.Response.ContentType = "application/pdf"
HttpContext.Current.Response.AppendHeader("Content-Disposition", "inline; filename=" + filename)
HttpContext.Current.Response.BinaryWrite(mem.ToArray)
HttpContext.Current.Response.OutputStream.Flush()
HttpContext.Current.Response.OutputStream.Close()
HttpContext.Current.Response.OutputStream.Dispose()
End Using
End Sub
Actually I'm not sure whether it is a good idea to Close and Dispose the response output stream here, that shouldn't be the responsibility of a PDF merging method.
This is a related answer for the Java version of iText; you may want to read it for additional information. Unfortunately many links in that answer meanwhile are dead.

Upload and replace the same image file if it already exist

I have a picturebox named PB_Company_Logo and I have a button named btn_Save and within this button I have this function which saves the image in PB_Company_Logo to current_directory/images
Public Sub save_PB(PB_Name As PictureBox)
Dim filename As String = "company_logo.png"
Dim path As String = Directory.GetCurrentDirectory() & "\images"
Dim filename_path As String = System.IO.Path.Combine(path, filename)
If (Not System.IO.Directory.Exists(path)) Then
System.IO.Directory.CreateDirectory(path)
PB_Name.Image.Save(filename_path)
Else
PB_Name.Image.Save(filename_path)
End If
End Sub
The problem is, there are cases where the user will upload a new company_logo.png. I want the system to treat the uploading of new image as replacing the former company_logo.png.
I think the error in this line of code means that the file is currently in used (locked) and therefore cannot be replaced.
Else
PB_Name.Image.Save(filename_path)
End If
When you load a pictureBox control with an image file the ide (vs) puts a lock on the file. This happens when you set the image property of the pictureBox control to a file at design time.
You can use the FileStream object.
Example:
Dim fs As System.IO.FileStream
' Specify a valid picture file path on your computer.
fs = New System.IO.FileStream("C:\WINNT\Web\Wallpaper\Fly Away.jpg",
IO.FileMode.Open, IO.FileAccess.Read)
PictureBox1.Image = System.Drawing.Image.FromStream(fs)
fs.Close()
After you have done the workaround you can then use the System.IO.File.Exists(img) namespace to check wether or not a picture exists.
Example: This checks if the image passed through already exists and if it does then it will replace it.
Dim imageStr As String = "~/images/name.jpg"
If System.IO.File.Exists(imageStr) Then
Image1.ImageUrl = "~/images/name.jpg"
End If

Retrieving images from a database?

I'm new to the forums and wanted to ask a question that has been bugging me for ages. I am using Visual Studio express 2012 with Windows Forms.
I want to have a database consisting of different images. Each row has its own image, and the other fields in the row define the images characteristics (I.E. Colour = Red, Striped = Yes etc) and its own specific ID.
Now what I want to do is allow the user to search via the form (Selecting what characteristics they want the image to have based on options on the form and then using SQL statements to retrieve the images based on their inputs). The only issue I am having is displaying all of the images on the form when they have searched? Is there any idea as to how to do this dynamically?
I created a form with FlowLayoutPanel in it. I set its AutoScroll property to true so that if there more pictures than fit in the space, it'll show a scroll bar so you can see them all.
I'm not entirely sure how you're getting the image, but assuming you have a function that returns a list of images.
Private Function DoImageSearch(parameters As SearchParameters) As List(Of Image)
'Go get images from database
End Function
Then you could have a function like the following to dynamically create PictureBox controls to be added to the FlowLayoutPanel.
Private Sub DynamicallyCreatedPictureBoxes(images As List(Of Image))
For Each image In images
Dim picture = New PictureBox()
picture.Image = image
picture.Size = image.Size
FlowLayoutPanel1.Controls.Add(picture)
Next
End Sub
In this case I've set the size of the PictureBox to be the size of the image. You may want to try to scale them or make thumbnails, but I'll leave that up to you (or another question). You'd probably also want another method to clear the images.
Private Sub ClearPictureBoxes()
FlowLayoutPanel1.SuspendLayout()
For Each control As Control In FlowLayoutPanel1.Controls
control.Dispose()
Next
FlowLayoutPanel1.Controls.Clear()
FlowLayoutPanel1.ResumeLayout()
End Sub
I'm not confident that last method is entirely correct, but you'd probably want something close to it.
Try like the this,
If color_RadioButton.Checked = True and type_RadioButton.Checked = True Then
cmdTect="color='" & color_RadioButton.Text & "' and type='" & type_RadioButton.Text & "'"
ElseIf color_RadioButton.Checked = True and type_RadioButton.Checked = False Then
cmdTect="color='" & color_RadioButton.Text & "'"
ElseIf color_RadioButton.Checked = False and type_RadioButton.Checked = TrueThen
cmdTect="type='" & type_RadioButton.Text & "'"
End If
dim cmd as new sqlcommand("select count(photo) from tbl where " & cmdTect,conn)
dim cnt as integer=cmd.ExecuteScalar()
for i as integer=0 to cnt
cmd = New SqlCommand("select photo from tbl where" & cmdTect,conn)
Dim imageData As Byte() = DirectCast(cmd.ExecuteScalar(), Byte())
If Not imageData Is Nothing Then
Dim ms As New MemoryStream(imageData, 0, imageData.Length)
ms.Write(imageData, 0, imageData.Length)
Dim pic As New PictureBox
pic.BackgroundImage = Image.FromStream(ms, True)
Panel1.Controls.Add(pic)
End If
Next

In Listview assign each item (a folder) an image from with each folder

I am developing an application to find, play and display all media, but primarily music. I am using Visual Studio 2012 in vb.net. On my form I have a Windows Media Player (WMP) and two listviews. The first listview (lvFolders) displays all folders of drive location. When I select a folder it automatically loads all files (media tracks) into the second listview (lvPlaylist), and starts playing the first track using the WMP. That all works well.
In each of these folders (500+) I have a cover of the respective album named "front.bmp". I cannot for the life of me work out what I am doing wrong. As the listview is populating the folders I am trying for it to load each image file located within that folder into the imagelist, and display the folders as large icons using that image. The result would be 500+ large folders each displaying their respective album cover from the imagelist.
I specifically didn't want to use Folder Browser Dialog or Open File Dialog. This application is for a touch based application for my own personal use.
I have attached my code in case it helps understand my dilemma.
Private Sub LoadFolders_Click(sender As Object, e As EventArgs) Handles btnLoadFolders.Click
For Each strDir As String In My.Computer.FileSystem.GetDirectories("E:\Music\TEST")
Dim imageListLarge As New ImageList()
Dim strAlbumArt As String = strDir & "\" & (My.Computer.FileSystem.GetName(strDir)) & ".bmp" 'URL of the image
imageListLarge.ColorDepth = ColorDepth.Depth32Bit 'Set the colour
imageListLarge.ImageSize = New Size(128, 128) 'Set image size
imageListLarge.Images.Add(strAlbumArt, Image.FromFile(strAlbumArt)) 'Add image to image list
lvFolders.LargeImageList = imageListLarge 'Assign the imagelist to the listview
Dim NewItem As New ListViewItem(My.Computer.FileSystem.GetName(strDir), strAlbumArt) 'Create Column 1 data
NewItem.SubItems.Add(My.Computer.FileSystem.GetFileInfo(strDir).FullName) 'Create Column 2 data
lvFolders.Items.Add(NewItem) 'Load into listview
Next
End Sub
Dim strAlbumArt As String = strDir & "\" & (My.Computer.FileSystem.GetName(strDir)) & ".bmp"
doesn't have "front.bmp" in it. Are you sure you don't mean something like Dim strAlbumArt As String = strDir & "\front.bmp?