Can you remove the alpha channel in a PNG with SIP

2019-07-29 04:46发布

Trying to stay native in SIPS when removing the alpha channel from images I am familiar with the process in ImageMagick with:

convert -flatten test.png test-white.png

or:

convert test.png -background white -alpha remove test.png

but when I reference the man page on ss4 and Library it tells me that hasAlpa is a boolean read only when I run:

sips -g hasAlpha test.png

Per searching under the tag and with:

there wasn't anything mentioned for removing transparency. Can you remove transparency with SIPS?

3条回答
Luminary・发光体
2楼-- · 2019-07-29 05:23

You could use the following little script, which uses OSX's built-in PHP which includes GD by default, so you would be staying native and not need ImageMagick or anything extra installed:

#!/usr/bin/php -f

<?php
// Get start image with transparency
$src = imagecreatefrompng('start.png');

// Get width and height
$w = imagesx($src);
$h = imagesy($src);

// Make a blue canvas, same size, to overlay onto
$result = imagecreatetruecolor($w,$h);
$blue = imagecolorallocate($result,0,0,255);
imagefill($result,0,0,$blue);

// Overlay start image ontop of canvas
imagecopyresampled($result,$src,0,0,0,0,$w,$h,$w,$h);

// Save result
imagepng($result,'result.png',0);
?>

So, if I start with this, which is transparent in the middle:

enter image description here

I get this as a result:

enter image description here

I made the canvas background blue so you can see it on StackOverflow's white background, but just change lines 12 & 13 for a white background like this:

...
...
// Make a white canvas, same size, to overlay onto
$result = imagecreatetruecolor($w,$h);
$white = imagecolorallocate($result,255,255,255);
imagefill($result,0,0,$white);
...
...

I did another answer here in the same vein to overcome another missing feature in sips.

查看更多
狗以群分
3楼-- · 2019-07-29 05:32

Using ImageMagick or GraphicsMagick would be better idea, but if you really want to use SIPS, you could try to remove transparency by converting image to BMP, and then back to PNG again:

sips -s format bmp input.png --out tmp.bmp
sips -s format png tmp.bmp --out output.png

Unfortunately you cannot choose background color, transparent parts of image will be replaced with black.

查看更多
冷血范
4楼-- · 2019-07-29 05:38

Another option, which is much lighter weight than installing the entire ImageMagick might be to use the NetPBM suite:

pngtopam -background=rgb:ff/ff/ff -mix start.png | pnmtopng - > result.png 

You can easily install NetPBM using homebrew with:

brew install netpbm
查看更多
登录 后发表回答