Convert ico file to png Visual Basic - visual-studio-2010

I am Looking for Code in VB that convert Ico File to other Format such as:
Jpg,JPEG,BMP,PNG
someone know such thing like that?
i tried it:
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim ImageUrl As String
ImageUrl = "C:\Arto.ico"
Dim str As Integer
str = InStr(ImageUrl, ".ico")
If (str > 0) Then
Dim b As New Bitmap(ImageUrl)
Dim newurl = Mid(ImageUrl, 1, Len(ImageUrl) - 4)
newurl = newurl + ".jpg"
b.Save(newurl) <<<<error here
' newurl = Mid()
' b.Save()
End If
End Sub
and that it the error i got:
An unhandled exception of type 'System.Runtime.InteropServices.ExternalException' occurred in System.Drawing.dll
Additional information: A generic error occurred in GDI+.

There is no image codec for icons. It is a pretty non-trivial format that can store multiple images and has 3 bitmaps for each image, one that contains the image pixels and two monochrome bitmaps that indicate which pixels are transparent and which are inverted. The Image class just doesn't have the plumbing in place to fully specify the properties that are needed to faithfully generate an .ico file.
But you're ahead since you want a PNG of JPEG file. You can create a bitmap that has the same size as the icon and draw the icon into that bitmap. A very important and non-trivial selection you need to make is choosing a background color for the image. Required because icons have transparency so you'll see the background on which it is displayed. Some image formats, like JPEG, don't support transparency. You have to pick one, Color.White tends to be okayish since that's the common background color for programs that display icons. You can use Color.Transparent for a PNG image.
Sample code:
Dim srce = "c:\temp\test.ico"
Dim dest = "c:\temp\test.jpg"
Using ico = New Icon(srce)
Using bmp = New Bitmap(ico.Width, ico.Height)
Using gr = Graphics.FromImage(bmp)
gr.Clear(Color.White) '' NOTE!
gr.DrawIcon(ico, 0, 0)
End Using
bmp.Save(dest, System.Drawing.Imaging.ImageFormat.Jpeg)
End Using
End Using

Related

Determine if TIFF image is grayscale or color using Visual Basic?

What Property or GetMethod can tell me whether a TIFF file is grayscale or color?
Is there some book that explains Palettes, PixelFormat, ImageAttributes, Flags?
The user may what/need to convert a color TIFF image to grayscale. How is this done
in Visual Basic?
Thru your help I found LibTiff. It answered almost all my questions. So here is some code that works.
Imports BitMiracle.LibTiff.Classic
Dim tifLeft As Tiff
Dim fileLeft As String
fileLeft = TNpath + "\" + fileNames(q)
tifLeft = Tiff.Open(fileLeft, "r") ' Tiff to read tags
' --- Get Gray or Color
Dim value = tifLeft.GetField(TiffTag.PHOTOMETRIC)
Dim GorC As Integer = value(0).ToInt()
imgLeftColor = False
If GorC > 1 Then
imgLeftColor = True
Else
imgLeftColor = False
End If

Calling PdfSharp xImg = XImage.FromFile(myImage) immediatly after Bitmap.Save(myImage, ImageFormat.Jpeg)

Good afternoon,
testing a my Window form application I noted an unexpected beaviour when coupling PdfSharp xImg = XImage.FromFile(myImage) with a preceding Bitmap.Save(myImage, ImageFormat.Jpeg).
Briefly:
I create a Bitmap from say 195202_000.jpg and then I save it as xxxx.jpg;
I create the Ximage.FromFile(xxxx.jpg) and add it to a Pdf in creation;
I create another Bitmap this time from 195202_001.jpg and I save it using again the name xxxx.jpg. No problems of overwriting occur.
I create the Ximage.FromFile(xxxx.jpg) and add it to the Pdf in creation;
I save the Pdf.
Well: at the end, xxxx.jpg contains correctly 195202_001.jpg, the Pdf file contains correctly two pages, but the Issue is that both the two pages contain 195202_000.jpg !!!
I do not understand where this issue raises.
If I change the name of the saved bitmap at every step (say xxxx1.jpg, xxxx2.jpg) all is fine.
Thanks for any help.
Paolo.
I attach the rough code used for producing and analizing the issue.
Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
Dim pdf As New PdfDocument
Dim fArray(1) As String
'TWO images.jpg PathName in array
fArray(0) = "C:\Users\Administrator\Desktop\myTestInp\195202_000.jpg"
fArray(1) = "C:\Users\Administrator\Desktop\myTestInp\195202_001.jpg" `
'Looping the array: creat bitmap from each image in fArray(), draw and save it as a new jpg,
'immediatly(re - Load) the new jpeg for adding it to a Pdf.
'Issue that I noted occurs when using the same PathName for saving and re-loading the image.
'Please see below.
For i As Integer = 0 To 1
'CREATE BitmapInp from fArray(i)
Dim BitmapInp As Bitmap = New Bitmap(fArray(i))
'DRAW BitmapOut
Dim BitmapOut As New Bitmap(BitmapInp.Width, BitmapInp.Height)
Dim grBitmapOut = Graphics.FromImage(BitmapOut)
grBitmapOut.DrawImage(BitmapInp, 0, 0, BitmapInp.Width, BitmapInp.Height)
grBitmapOut.Dispose()
BitmapInp.Dispose()
'SAVE BitmapOut as "C:\Users\Administrator\Desktop\myTestOut\xxxx.jpg"
'NOTE: each time, the Bitmap is saved using the same file name above.
'overwriting does not raise errors.
BitmapOut.Save("C:\Users\Administrator\Desktop\myTestOut\xxxx.jpg", ImageFormat.Jpeg)
BitmapOut.Dispose()
'LOAD BitmapOut as xImg from "C:\Users\Administrator\Desktop\myTestOut\xxxx.jpg"
'NOTE: FromFile just saved
Using xImg = XImage.FromFile("C:\Users\Administrator\Desktop\myTestOut\xxxx.jpg")
Dim page = pdf.AddPage()
Dim grPdf = PdfSharp.Drawing.XGraphics.FromPdfPage(page)
page.Width = 500 * 72 / xImg.HorizontalResolution
page.Height = 500 * 72 / xImg.HorizontalResolution
xImg.Interpolate = False
grPdf.DrawImage(xImg, 0, 0, page.Width, page.Height)
End Using
Next
'END of loop
'SAVE Pdf
pdf.Save("C:\Users\Administrator\Desktop\myTestOut\Dummy.Pdf")
'Issue: the Pdf contains correctly two pages, but they are equals! And precisely is
' the first image that occurs two times!
End Sub
I didn't check the source code of PDFsharp/MigraDoc, but maybe the filename is used as a "unique key" to prevent incorporating multiple copies of the same image into one PDF file.
If the same image is used on multiple pages, only one copy of the image data is included in the file.
I know that PDFsharp tries to prevent multiple copies - and IIRC the filename is the key.
And yes, using different file names should resolve the issue.

Changing image Appearance and BorderStyle only works sometimes?

I'm trying to use the Appearance and BorderStyle properties of the image control to provide a not selected/selected indicator.
After image is loaded and displayed in the not selected condition, I can change Appearance and BorderStyle to 1 and it displays properly. But subsequent changes of these properties back to 0 has no effect.
Public Sub SelectPic(obj As Object, SelectIt As Boolean)
Dim Val As Integer
If SelectIt Then
Val = 1 'this works
Else
Val = 0 'this doesn't work
End If
obj.Appearance = Val
obj.BorderStyle = Val
obj.Refresh
End Sub
If I load a .bmp file into an image with flat appearance and no border, the image displays in agreement with the .bmp sizing info. But if load into an image with 3D appearance and single border, it displays according to the defined image size. Changing the properties back to flat and no border has no effect.

VBA download and embed images using url from adjacent cell

I've attempted the solution in the following.
Inserting an Online Picture to Excel with VBA
Unfortunately I get a run-time error '1004'
"Unable to get the Insert property of the Picture class"
which stops on the following code :
Set myPicture = ActiveSheet.Pictures.Insert(pic)
Could this be due to my Office version 2016 (64bit) ?
If not, are there any suggestions of how I might get embed images to adjacent cells in column AK using the image urls from column AJ ?
Thanks in advance
There's some evidence that Excel has trouble downloading from AWS, and I've recreated your issue using the URL you mentioned. In this case, if I were on a deadline I'd put in this fall-back method when the first one fails: download the file, then insert it into the document, then delete the file.
directDownloadFailed:
Dim FileNum As Long
Dim TempFile As String
Dim FileData() As Byte
Dim WHTTP As Object
Set WHTTP = CreateObject("WinHTTP.WinHTTPrequest.5.1")
WHTTP.Open "GET", imgURL, False
WHTTP.Send
FileData = WHTTP.ResponseBody
Set WHTTP = Nothing
FileNum = FreeFile
TempFile = "path\to\save\img.jpg"
Open TempFile For Binary Access Write As #FileNum
Put #FileNum, 1, FileData
Close #FileNum
Set img = ActiveSheet.Pictures.Insert(TempFile)
SetAttr TempFile, vbNormal
Kill TempFile
GoTo resumeProcessingImg
#keydemographic
I appreciate the response and that definitely sounds like an option but I cannot get that code to work or incorporate it into the code I'm using. I get a compile error "Label Not defined" on GoTo resumeProcessingImg
The following will download and embed the images into the cells but the code stops once it gets to the s3 aws image urls.
I'll try a few other ways to incorporate your code but I'm not having much luck with it so far.
This is my test file
Sub URL2IMG()
Dim pic As String 'path of pic
Dim myPicture As Picture 'embedded pic
Dim rng As Range 'range over which we will iterate
Dim cl As Range 'iterator
Set rng = Range("b2:b12") '<~~ as needed, Modify range to where the images are to be embedded.
For Each cl In rng
pic = cl.Offset(0, -1) '<~~ defines image link URL in column to the left of the embedded column
Set myPicture = ActiveSheet.Pictures.Insert(pic)
'you can play with the following to manipulate the size & position of the picture.
With myPicture
.ShapeRange.LockAspectRatio = msoFalse
' currently this shrinks the picture to fit inside the cell.
.Width = cl.Width
.Height = cl.Height
.Top = Rows(cl.Row).Top
.Left = Columns(cl.Column).Left
End With
Next
End Sub

Is there a way to read images from a folder and save it in powerpoint

I have approx. 100 images , I want to read those images, do the resizing and save it in a power point using matlab, Is it way to save those images in a power point giving title to each slide.
I am reading images using this code:
for i = 1:numel(pngfiles)
im{i} = imread(pngfiles{i});
imrgb{i} = rgb2gray(im{i});
imrgb_z{i} = imrgb{i}(160:350,280:450);
end
It seems to me that the best approach would be to use a VBA script inside Powerpoint, rather than manipulating ppt from Matlab. The steps would be
Create your list of images in a folder - using a sensible naming scheme
Open Powerpoint; go to the VBA editor (Alt-F11) and add a module with the following lines of code in it (note - this is taken straight from https://stackoverflow.com/a/5038907/1967396 with minimal edits):
-
Sub CreatePictureSlideshow( )
Dim presentation
Dim layout
Dim slide
Dim FSO
Dim folder
Dim file
Dim folderName
Dim fileType
' Set this to point at the folder you wish to import JPGs from
' Note: make sure this ends with a backslash \
fileType = ".jpg" ' <<< change this to the type you want
folderName = "c:\somedirectory\" ' <<< change this to the directory you want
' setup variables
Set presentation = Application.ActivePresentation
' choose the layout you want: e.g. if the title needs a particular format
Set layout = Application.ActivePresentation.SlideMaster.CustomLayouts(1)
Set FSO = CreateObject("Scripting.FileSystemObject")
' Retrieve the folder's file listing and process each file
Set folder = FSO.GetFolder(folderName)
For Each file In folder.Files
' Filter to only process JPG images
If LCase(Right(file.Name), 4)) = fileType Then
' Create the new slide and delete any pre-existing contents
Set slide = presentation.Slides.AddSlide(presentation.Slides.count + 1, layout)
While slide.Shapes.count > 0
slide.Shapes(1).Delete ' <<< You might not want to do this is you want to keep the title placeholder
Wend
' Add the picture
slide.Shapes.AddPicture folderName + file.Name, False, True, 10, 10
' Optional: create a textbox with the filename on the slide for reference
' alternatively, add text to the title shape
Dim textBox
Set textBox = slide.Shapes.AddTextbox(msoTextOrientationHorizontal, 10, 10, 200, 200)
textBox.TextFrame.TextRange.Text = file.Name ' <<< or whatever "title" you wanted
End If
Next
End Sub
You can modify this further to get the title in the format you want, etc.
you could try this:
Is there an example of using MATLAB to create PowerPoint slides?
For example:
% before the following, you have to create the ppt as explained, see link above!
% I prefer using some name instead of i or j
for img_ind = 1:numel(pngfiles)
% this depends on the ppt-version (see link above)-> here for 2007 and higher
mySlide = Presentation.Slides.Add(1,'ppLayoutBlank')
% Note: Change the image file full path names to where you save them
Image1 = mySlide.Shapes.AddPicture('<full path>\name_of_image(img_ind).png','msoFalse','msoTrue',100,20,500,500)
end
% then you have to save it, see link above!
In your case, I guess you have to save the image first as shown in the example:
print('-dpng','-r150','<full path>\test1.png')
edit
This will only work when using Matlab on Windows, because COM is needed. See comments on Floris answer!
Coming late to this party: Here's a "Matlab Pick of the Week" tool:
http://www.mathworks.com/matlabcentral/fileexchange/30124-smart-powerpoint-exporter
Take note of some of the comments at that page, as apparently the tool has not been updated in a few years.

Resources