Page 1 of 1

VBA get transparency

Posted: 2016-10-04T12:35:44+00:00
by scar12
I’ve been struggling for several days with an issue. I’ve read a lot of forum posts but didn’t find any solution for the moment.

I’m programming on VBA. I want to know wether an image has transparency (i.e. alpha channel present and transparent pixels). I use the IM command proposed here viewtopic.php?t=18596 :

Code: Select all

convert image.png -alpha on -alpha extract -format "%[fx:mean]" info:
This code gives the mean of the alpha pixels.

I call this command from VBA, usint "WScript.Shell" :

Code: Select all

Set shellCommand = VBA.CreateObject("WScript.Shell")
cmdLine = “convert image.png -alpha on -alpha extract -format "%[fx:mean]" info: > C:\tempfile.txt”
windowStyle = 0
waitOnReturn = True
returnCode = shellCommand.Run("%comspec% /c " & cmdLine, intWindowStyle, bWaitOnReturn)

I use shellCommand.Run and not shellCommand.Exec, because I want the shell window not to be visible and it seems only feasible with Run.
To get the result of the shell command, I forward it to a text file (I would have preferred to get the result directly, but didn’ find the way to do it).

The problem with the above code is that the tempfile.txt is created, but it is empty. Do you have any idea why ?
By the way I’ve tested the command directly from the DOS command prompt, and it works : the tempfile.txt contains the result.

Re: VBA get transparency

Posted: 2016-10-04T15:33:47+00:00
by snibgo
Check the value that is assigned to cmdLine. As the double-quote terminates the string, you'll need to do something special to put one inside the string, eg by doubling it.

Re: VBA get transparency

Posted: 2016-10-05T11:17:21+00:00
by scar12
You're right, thank you for your answer. I actually have to put double quotes here : ""%[fx:mean]""
But it works only if I use DOS path for convert.exe. E.g. :

Code: Select all

cmdLine = "C:\Progra~1\ImageMagick-7.0.3-Q16\convert.exe  image.png -alpha on -alpha extract -format ""%[fx:mean]"" info: > C:\tempfile.txt"
But If I use windows full path (containing space), it doesn't work. I've tested putting two double quotes around it :

Code: Select all

cmdLine = """C:\Program files\ImageMagick-7.0.3-Q16\convert.exe"" image.png  -alpha on -alpha extract -format %[fx:mean]"" info: > C:\tempfile.txt"
It doesn't work neither.

Any idea ?

Re: VBA get transparency

Posted: 2016-10-05T12:32:44+00:00
by snibgo
In you second command, look at the format. Can you see the problem?

Re: VBA get transparency

Posted: 2016-10-05T12:49:18+00:00
by scar12
Sorry, I made a mistake copying the code from my VB editor to the forum, and forgot to type "" before %[fx:mean]"". Actually, my code was :

Code: Select all

cmdLine = """C:\Program files\ImageMagick-7.0.3-Q16\convert.exe"" C:\image.png  -alpha on -alpha extract -format ""%[fx:mean]"" info: > C:\tempfile.txt"