saving image type with its original file type - vb.net

i needed to save an image into my vb proj. I am using a process to save an image to a local folder using it's file name. However, to do it my code has to convert the format to .jpg. What i needed was to save the file with it's original type, since my project will be receiving different image type and maps as well as .pdf in it. is there any way i could change the imageformat.jpegto something else that will save the image to it's original format?
this is the code i am using to save the image.
to create directory
If (Not System.IO.Directory.Exists("d:/Site Images/" & Label33.Text & "/")) Then
System.IO.Directory.CreateDirectory("d:/Site Images/" & Label33.Text & "/")
End If
to save the image
Upload.PictureBox1.Image.Save("d:/Site Images/" & Label33.Text & "/" + Upload.TextBox1.Text, System.Drawing.Imaging.ImageFormat.Jpeg)
i am using MSVisual Studio 2013 Ultimate.
thanks

One method to do this would be that when you load the image into the picturebox you can save the original extension in the tag:
Dim sFilename As String = "c:\test.png" ' However you are populating your picturebox, you can change this variable to the full path of the file
Upload.PictureBox1.Image = Image.FromFile(sFilename)
Upload.PictureBox1.Tag = System.IO.Path.GetExtension(sFilename).ToLower ' Saves the extension to the picturebox in the tag field so that we can evaluate it later
Then when you need to save the image back to a file, you can write it back in the same image format as before:
' Figure out what the original image format was
Dim oImageFormat As System.Drawing.Imaging.ImageFormat
Select Case PictureBox1.Tag.ToString
Case ".jpeg", ".jpg"
oImageFormat = System.Drawing.Imaging.ImageFormat.Jpeg
Case ".png"
oImageFormat = System.Drawing.Imaging.ImageFormat.Png
Case ".bmp"
oImageFormat = System.Drawing.Imaging.ImageFormat.Bmp
Case ".gif"
oImageFormat = System.Drawing.Imaging.ImageFormat.Gif
Case ".tif", ".tiff"
oImageFormat = System.Drawing.Imaging.ImageFormat.Tiff
Case ".ico", ".icon"
oImageFormat = System.Drawing.Imaging.ImageFormat.Icon
Case ".emf"
oImageFormat = System.Drawing.Imaging.ImageFormat.Emf
Case ".exif"
oImageFormat = System.Drawing.Imaging.ImageFormat.Exif
Case ".wmf"
oImageFormat = System.Drawing.Imaging.ImageFormat.Wmf
Case Else
' This should never happen but just in case the extension cannot be found we default to jpeg output
oImageFormat = System.Drawing.Imaging.ImageFormat.Jpeg
End Select
' Save the image with in the proper format again
Upload.PictureBox1.Image.Save("d:/Site Images/" & Label33.Text & "/" & Upload.TextBox1.Text & PictureBox1.Tag.ToString, oImageFormat)
Notes regarding pdf: The Picturebox control does not support pdf files and therefore you will not be able to load pdfs this way. I suggest you convert the pdf to an image file that is supported and then load it into your app after conversion. If this isn't feasible you will have to choose a different control to handle your pdfs such as the WebBrowser control.

You can check the file extension to see what the original image file format is. When you save the file, you can specify the original format in the Picturebox Image.Save function, such as System.Drawing.Imaging.ImageFormat.Png.
If that format is not supported by .net (see link below), you can use a third-party library such as freeImage.
https://msdn.microsoft.com/en-us/library/system.drawing.imaging.imageformat%28v=vs.110%29.aspx

Related

VBA runtime error 3625 The text file specification Export_Spec does not exist

I am running Access 2016. I am trying to export the results of a query into a text file, I keep on getting an error 3625 no spec is found. I created the spec and if I run the spec it works as expected. I tried putting quotes instead of the export spec, but there was no formatting on the file. The solutions I found on the web were saying to use the advanced tab to define formatting, On my version of Access 2016 there is no advanced tab in the spec creation process. I have stepped through the process and all the directories and the file name is created properly.
The error occurs on the line :
DoCmd.TransferText TransferType:=acExportDelim, SpecificationName:=strExportSpec, TableName:=strQueryName, FileName:=strFullName, HasFieldNames:=True
Any help is appreciated.
Private Sub Export_Click()
Dim strFileName As String
Dim lFileName As Long
Dim strCurrentDate As String
Dim strFormattedDate As String
Dim dtCurrentDate As Date
Dim strDir As String
Dim strFullName As String
Dim strExportSpec As String
Dim strQueryName As String
Dim strYear As String
Dim strMonth As String
Dim strPath1 As String
Dim strPath2 As String
strYear = Format(Date, "yyyy")
strMonth = Format(Date, "mm")
'Check if Directory Year exists
strPath1 = "C:\Users\Owner\Google Drive\Employment\Mass Unemployment\" & strYear
'Check if year exists
If Dir(strPath1, vbDirectory) = "" Then
MkDir strPath1
End If
'Create
strPath2 = "C:\Users\Owner\Google Drive\Employment\Mass Unemployment\" & strYear & "\" & strMonth & "\"
If Dir(strPath2, vbDirectory) = "" Then
MkDir strPath2
End If
strCurrentDate = Date
strFormattedDate = Format(strCurrentDate, "mmddyyyy")
lFileName = InputBox("Enter Week Number", "Enter Week Number")
strFileName = strFormattedDate
strFullName = strPath2 & strFileName & ".txt"
strExportSpec = "Export_Spec" ' error 3625 export spec does not exist
strQueryName = "qryUnEmployment"
DoCmd.TransferText TransferType:=acExportDelim, SpecificationName:=strExportSpec, TableName:=strQueryName, FileName:=strFullName, HasFieldNames:=True
End Sub
I believe what Parfait is telling you is that the Saved Import/Saved Exports are far different than an Import/Export Specification. You are trying to put a Saved Export into the TransferText parameter where a Specification is called for. You likely did an export at some point and saved the steps as a Saved Export.
If you're truly interested in using a specification for this export then you will want to create one by walking through the import of an already existing text file in the format you would like. See Parfait answer above.
Otherwise, just leave the specification parameter blank and the query will be exported.
The Save Import/Export GUI frontend feature and the backend method, DoCmd.TransferText refer to different specification types. The former is more a saved routine as a convenience method to retrieve the same named text, spreadsheet, or XML file and all the steps to import or export the external data and avoid the walk through of wizard in future runs.
However, the latter is specific to formatting of any text file and it is usually created during the text file wizard under Advanced button. See screenshot below. In this dialog you can specify formats for each field, delimiters, etc. and then either run the specification one time or Save As... for future uses on any text file. In fact, Specs... shows a current list of all saved named specifications. It is here where you can find the name to use in DoCmd.TransferText.
Import Text Wizard
Export Text Wizard
To date, there may not be any other GUI way to adjust these saved specifications. They are stored in system tables, MSysIMEXspecs and MSysIMEXColumns. Again, do not confuse above text file specific method for the generalized external data methods: ImportExportSpecifications and DoCmd.RunSavedImportExport.

Trying to save a pdf file of a screenshot of the form, given a specified location from the user's input

I am trying to save a created, PDF file to a location specified by the user. I'm using Visual Studio Community 2019. Essentially, I am taking a screenshot of this form:
And by using the PdfSharp external library, I create a PDF file and then save that PDF to some file location specified by the user. Here is the UI for the user to select their preferred file location:
The issue arises once the program tries to save the PDF file to the location given by the user. Here is the error I get from Visual Studio:
System.NotSupportedException: 'No data is available for encoding 1252. For information on defining a custom encoding, see the documentation for the Encoding.RegisterProvider method.'
I looked online for this specific error, but I don't really understand it nor what to do with it, it's very confusing. I'm still a bit of beginner when it comes to working with Visual Basic. Here's the code that tries to do it:
Dim fileLocation As String
fileLocation = folderBrowseBox.Text
GetFormImage(True).Save(fileLocation & "\" & RemoveWhitespace(filename) & "_" & RemoveWhitespace(collectionPeriod) & ".jpg", ImageFormat.Jpeg)
' Create new pdf document and page
Dim doc As New PdfDocument()
Dim oPage As New PdfPage()
' Add the page to the pdf document and add the captured image to it
doc.Pages.Add(oPage)
Dim img As XImage = XImage.FromFile(fileLocation & "\" & RemoveWhitespace(filename) & "_" & RemoveWhitespace(collectionPeriod) & ".jpg")
'Create XImage object from file.
Using xImg = PdfSharp.Drawing.XImage.FromFile(fileLocation & "\" & RemoveWhitespace(filename) & "_" & RemoveWhitespace(collectionPeriod) & ".jpg")
'Resize page Width and Height to fit image size.
oPage.Width = xImg.PixelWidth * 72 / xImg.HorizontalResolution
oPage.Height = xImg.PixelHeight * 72 / xImg.HorizontalResolution
'Draw current image file to page.
Dim xgr = PdfSharp.Drawing.XGraphics.FromPdfPage(oPage)
xgr.DrawImage(xImg, 0, 0, oPage.Width, oPage.Height)
End Using
doc.Save(fileLocation & "\" & RemoveWhitespace(filename) & "_" & RemoveWhitespace(collectionPeriod))
img.Dispose()
The second to last line of code ("doc.Save(fileLocation & ...)") is where the error occurs. The folderBrowseBox.Text (very first line of code) comes from the textbox you see from my second screenshot. Any help/advice will be greatly appreciated!
Try adding this line before writing the PDF file
System.Text.Encoding.RegisterProvider(System.Text.CodePagesEncodingProvider.Instance)
Got the idea from here

How to make pdf file size with respect to div height and width using wkhtmltopdf.exe

I tried to make pdf with wkhtmltopdf.exe by supplying html string and is working properly.But i want to provide pdf custom size to exe.
eg:-
Suppose i have a div of height 30 and width 50. then the generated pdf should be of same size.
Below is the code which i found from this website forum
Private Sub WritePDF(ByVal HTML As String)
Dim inFileName As String, outFileName As String, tempPath As String
Dim p As Process
Dim stdin As System.IO.StreamWriter
Dim psi As New ProcessStartInfo()
tempPath = Server.MapPath("~") + "\Uploads\"
inFileName = Session.SessionID + ".htm"
outFileName = Session.SessionID + ".pdf"
' run the conversion utility
psi.UseShellExecute = False
'psi.FileName = "c:\Program Files (x86)\wkhtmltopdf\wkhtmltopdf.exe"
psi.FileName = Server.MapPath("~") + "\App_Data\wkhtmltopdf.exe"
psi.CreateNoWindow = True
psi.RedirectStandardInput = True
psi.RedirectStandardOutput = True
psi.RedirectStandardError = True
' note that we tell wkhtmltopdf to be quiet and not run scripts
' NOTE: I couldn't figure out a way to get both stdin and stdout redirected so we have to write to a file and then clean up afterwards
psi.Arguments = "-q -n - " & tempPath & outFileName
p = Process.Start(psi)
Try
stdin = p.StandardInput
stdin.AutoFlush = True
stdin.Write(HTML)
stdin.Close()
If p.WaitForExit(15000) Then
' NOTE: the application hangs when we use WriteFile (due to the Delete below?); this works
'Response.WriteFile(tempPath + outFileName);
Response.BinaryWrite(System.IO.File.ReadAllBytes(tempPath & outFileName))
End If
Finally
p.Close()
p.Dispose()
End Try
' delete the pdf
System.IO.File.Delete(tempPath & outFileName)
End Sub
If you want to use a standard paper size you can use the --page-size argument and provide the page size name (A4, Letter, etc.). If you want a custom page size, you can use the --page-width and --page-height arguments (e.g. --page-width 100mm --page-height 200mm).
By default, wkhtmltopdf will add a margin around each side of the page, which is used to render the header and footer in. To change the page margins, use the arguments --margin-top, --margin-right, --margin-bottom and --margin-left.
Another thing to note is the --disable-smart-shrinking; by default, wkhtmltopdf will 'guess' the dpi of the pdf by calculating the html widths and trying to fit it within the boundaries of the pdf page. If you want to precisely measure each element on the page, you should add --disable-smart-shrinking to your argument list. However, make sure the html output defines the exact size of the html page (which should be the same as the pdf page minus the page margins), otherwise wkhtmltopdf might not be able to render the page properly.

Why does my code throw a generic error in GDI+?

I'm trying to convert a batch of .pngs to .jpgs, as in this question:
For Each file As String In Directory.EnumerateFiles(path).Where(Function(s) s.EndsWith(".png"))
Dim newfile As String = IO.Path.Combine(newpath, IO.Path.GetFileNameWithoutExtension(file) & ".jpg")
Using png As Bitmap = Bitmap.FromFile(file)
Using jpg As New Bitmap(png.Width, png.Height)
Using g As Graphics = Graphics.FromImage(jpg)
g.Clear(Color.FromArgb(255, 212, 208, 200))
g.DrawImageUnscaled(png, 0, 0)
jpg.Save(newfile, ImageFormat.Jpeg)
End Using
End Using
End Using
Next
The call to jpg.Save, however, with a "generic error" in GDI+. Originally outside of the innermost Using statement, I moved the call inwards as per this answer, but it didn't change anything. I have verified that newfile contains a valid path, and that the program has write access to the directory. What am I missing?
I know you are saying that you are sure about the file path, but here I can see that newfile you are passing to the IO.Path.Combine have a null value.
I just initialize the newfile string with the Path string, and run your code successfully without any problem:
Dim newfile As String = Path
newfile = IO.Path.Combine(newpath, IO.Path.GetFileNameWithoutExtension(file) & ".jpg")
I've tried your code (rewritten in C#) and discovered one thing: the exception occurs only if you try to save the new image inside the same directory from which you are listing the PNGs. If you change the code to write images to a different directory, the code works without problems.
I cannot really give you an explanation of why this is happening (other than perhaps Bitmap.FromFile() is locking up the directory somehow). There are a lot of GDI+ Bitmap quirks.
BTW: I managed to rework my C# code so it doesn't throw exceptions, I'll rewrite your VB snippet in an analogous way (I haven't tested the VB code though):
For Each file As String In Directory.EnumerateFiles(path).Where(Function(s) s.EndsWith(".png"))
Dim newfile As String = IO.Path.Combine(newpath, IO.Path.GetFileNameWithoutExtension(file) & ".jpg")
Using jpg As New Bitmap(png.Width, png.Height)
Using g As Graphics = Graphics.FromImage(jpg)
Using png As Bitmap = Bitmap.FromFile(file)
g.Clear(Color.FromArgb(255, 212, 208, 200))
g.DrawImageUnscaled(png, 0, 0)
End Using
jpg.Save(newfile, ImageFormat.Jpeg)
End Using
End Using
Next
Hope it works.

Restrict Image by selecting it's URL

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