Calling ImageMagick COM from VBScript - vbscript

I have successfully used the following command line to create a new GIF image with some simple text
convert -size 100x100 -font arial label:blah output.gif
I would like to achieve the same result using the COM interface from VBScript, but have not been successful in passing in the same parameters in. Here is my code...
Dim img
Set img = CreateObject("ImageMagickObject.MagickImage.1")
Dim fnm(6)
fnm(0) = "-size"
fnm(1) = "100x100"
fnm(2) = "-font"
fnm(3) = "arial"
fnm(4) = "-label"
fnm(5) = "blah"
fnm(6) = "C:\temp\example.gif"
retval = img.convert(fnm)
wscript.echo("retval " & retval)
I execute this code as follows
cscript example.vbs
and the output I get is this, and no GIF file is created...
Microsoft (R) Windows Script Host Version 5.8
Copyright (C) Microsoft Corporation. All rights reserved.
Version: ImageMagick 6.7.4-3 2011-12-24 Q16 http://www.imagemagick.org
Copyright: Copyright (C) 1999-2012 ImageMagick Studio LLC
Features: OpenMP
Usage: cscript.exe [options ...] file [ [options ...] file ...] [options ...] file
I'm on Windows7 using ImageMagick-6.7.4-Q16
Does anyone know what I am doing wrong?
[Edit]
In response to Ekkehard's answer I have also tried not using an array. This code will create an output image, but the label is not applied. I also have to pass in a white image as an input as it will not work without one.
msgs = img.convert("C:\temp\blank.gif", "-size", "100x100", "-font", "arial", "label:", "blah", "C:\temp\example.gif")

In the end I gave up trying to get label to work when using the COM+ API and have a solution that uses -draw instead. Ekkehard was right about not using an Array, and instead use individual arguments as shown below.
msgs = img.convert( "c:\temp\blank.gif", "-font", "arial", "-pointsize", "36", "-gravity", "center", "-fill", "blue", "-draw", "text 0,0 'blah'", "c:\temp\example.gif")

In the folder [WhereEver]\ImageMagick-6.7.4-Q16\ImageMagickObject\Tests you'll find two sample scripts (ArrayTest.vbs, SimpleTest.vbs). The most important info from the second:
' The argument list is exactly the same as the utility programs
' as a list of strings. In fact you should just be able to
' copy and past - do simple editing and it will work. See the
' other samples for more elaborate command sequences and the
' documentation for the utility programs for more details.
'
msgs = img.Convert("logo:","-format","%m,%h,%w","info:")
So passing all params in one array is as wrong as attempting to set properties. I used
Dim sSrcFSpec : sSrcFSpec = "..\data\logo.jpg"
Dim sDstFSpec : sDstFSpec = "..\data\logo.png"
If goFS.FileExists(sDstFSpec) Then goFS.DeleteFile sDstFSpec
CreateObject("ImageMagickObject.MagickImage.1").convert "-verbose", sSrcFSpec, sDstFSpec
If Not goFS.FileExists(sDstFSpec) Then WScript.Echo "Failure!"
output:
..\data\logo.jpg JPEG 123x118 123x118+0+0 8-bit DirectClass 16.2KB 0.000u 0:00.006
..\data\logo.jpg=>..\data\logo.png JPEG 123x118 123x118+0+0 8-bit DirectClass 0.030u 0:00.
083
which proves that you'll get results if you pass reasonable arguments. I tried something similar to your test code -
convert -verbose -size 100x100 -font arial -label blah ..\data\example.gif
and got:
convert.exe: missing an image filename `..\data\example.gif' # error/convert.c/ConvertImag
eCommand/3016.
Knowing nothing about ImageMagick, I can only assume that such args assume an existing input file.
So do your COM testing when you have verified the parameters from the command line.

A COM interface is going to expose a series of properties and methods for controlling an object. You wouldn't instantiate it by passing an array of values. In most cases, you would set each property individually. It might look something this (purely an example, I don't know if these are real properties for this object):
Dim img
Set img = CreateObject("ImageMagickObject.MagickImage.1")
img.sizeX = 100
img.sizeY = 100
img.font = "Arial"
img.label = "blah"
retval = img.convert("C:\temp\example.gif")
WScript.echo("retval " & retval)
An object browser or type library viewer can be used to examine the COM object's properties and methods. My favorite is TLViewer.

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

How to convert imageSet to idx3-ubyte format, using mnisten,

I am trying to use a CNN code to train 10 images stored in an imageSet. The CNN code rather uses the idx3-ubyte format.
I want to know how to convert from my imageSet data to idx3-ubyte format.
I came across the mnisten command below, but I don't have any Idea how to use it.
Please help.
%Here is my imageSet code that I want to convert to idx3-ubyte format.
%% Load image dataset
imgFolder1 = fullfile('C:\Users\Jay\Desktop\practical-cnn-2015a\NairaNotes');
trainingSet = imageSet(imgFolder1, 'recursive');
%%
for digit = 1:numel(trainingSet)
numImages = trainingSet(digit).Count;
for i = 1:numImages
img = read(trainingSet(digit), i);
im = rgb2gray(im2single(read(trainingSet(digit), i)));
end
end
%% here is the mnisten command I got, but I don't have an idea how to use it
mnisten -d my_image_files_directory_name -o my_prefix -s 32x32
Since I assume you're on Windows, check out this guide.

Convert ico file to png Visual Basic

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

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.

How do I determine the image dimensions of a tiff file?

I have a vbscript script and I need to chew through a directory of .tif files. For each file, I need to determine if the file is proportioned as a landscape or a portrait. Basically, I need to be able to get the image dimensions for each file. So for, I have seen some examples of people reading the file file headers to extract this sort of information from jpg or bmp files. Has anyone done the same thing to extract the dimensions for a tiff file?
In VBScript, you can determine the image dimensions in two ways:
Using the WIA Automation Library (download link, MSDN documentation, an excellent Hey, Scripitng Guy! article on the subject). Once you have the wiaaut.dll library registered, you can use the following simple code:
Set oImage = CreateObject("WIA.ImageFile")
oImage.LoadFile "C:\Images\MyImage.tif"
WScript.Echo "Width: " & oImage.Width & vbNewLine & _
"Height: " & oImage.Height
Using the GetDetailsOf method to read the corresponding extended file properties. This is a native Windows scripting method, so no external libraries are required; but the code is longer:
Const DIMENSIONS = 31
CONST WIDTH = 162
CONST HEIGTH = 164
Set oShell = CreateObject ("Shell.Application")
Set oFolder = oShell.Namespace ("C:\Images")
Set oFile = oFolder.ParseName("MyImage.tif")
strDimensions = oFolder.GetDetailsOf(oFile, DIMENSIONS)
strWidth = oFolder.GetDetailsOf(oFile, WIDTH)
strHeigth = oFolder.GetDetailsOf(oFile, HEIGTH)
WScript.Echo "Dimensions: " & strDimensions & vbNewLine & _
"Width: " & strWidth & vbNewLine & _
"Height: " & strHeigth
This script outputs something like:
Dimensions: 2464 x 3248
Width: 2464 pixels
Height: 3248 pixels
so if you need plain numbers, you'll have to extract them from the returned strings.
There's also another problem with this method - the property indexes (those constants in the beginning on the script) are different in different Windows versions, as I explained in this answer. The above script is for Windows 7, but if you use another Windows versions or if you want the script to work on different Windows versions, you'll need to use version-specific indexes. The most complete list of available property indexes is here.
I would recommend using Atalasoft's DotImage Photo Its powerful & it's free! But, it's a .NET package, so you'll have do some Regasm Magic to make it work. Go check out Use vb.net in VBScript before you get started.
Here is the code you'll need to get the dimensions.
Public Function GetHeight(path As String) As Integer
Using stm As New FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read)
Dim decoder As New TiffDecoder()
If Not decoder.IsValidFormat(stm) Then
Throw New Exception("not a TIFF")
End If
Dim image As AtalaImage = decoder.Read(stm, Nothing)
Return image.Height
' Return image.Width --- To return the Width.
End Using
End Function

Resources