曾经遇到这样一些问题:
根据 ImageMagick 命令的中间操作结果 的介绍,答案是:
不要按照Fred's ImageMagick Scripts 脚本中的方法,多次调用convert 命令(即在C++代码中多次调用ConvertImageCommand() 函数),而是参考Fred's ImageMagick Scripts 每个特效的页面的最后一段文字中介绍的等价命令行,写出对应的命令行字符串,作为参数传给下面代码中的 IM_Convert() 函数。就这么简单!
例如,要消除mf-small.jpg 图片中的背景噪声,保存成mf-small-out.jpg,我们临摹 TEXTCLEANER 脚本等价命令行
convert \( $infile -colorspace gray -type grayscale -contrast-stretch 0 \) \ \( -clone 0 -colorspace gray -negate -lat ${filtersize}x${filtersize}+${offset}% -contrast-stretch 0 \) \ -compose copy_opacity -composite -fill "$bgcolor" -opaque none +matte \ -deskew 40% -sharpen 0x1 $outfile即传给IM_Convert() 函数的字符串是:
convert ( mf-small.jpg -colorspace gray -type grayscale -contrast-stretch 0 ) ( -clone 0 -colorspace gray -negate -lat 25x25+10% -contrast-stretch 0 ) -compose copy_opacity -composite -fill \"white\" -opaque none +matte -deskew 40% -sharpen 0x1 mf-small-out.jpg示例代码:
#include <wand/MagickWand.h> #include <string> #include <vector> #include <sstream> #include <iostream> #include <string.h> #include <stdlib.h> using namespace std; void AllocArg(const char* cmd, int &argc, char** &argv) { istringstream issCmd(cmd); string sPara; vector<string> vParas; argc = 0; while(issCmd >> sPara) { vParas.push_back(sPara); ++argc; } argv = (char**)malloc(argc * sizeof(char*)); for(int i = 0; i < argc; ++i) { argv[i] = (char*)malloc(vParas[i].size() + 1); strcpy(argv[i], vParas[i].c_str()); } } void FreeArg(int &argc, char** &argv) { if(argv != NULL) { for(int i = 0; i < argc; ++i) { free(argv[i]); } free(argv); argv = NULL; } } MagickBooleanType IM_Convert(const char* cmd) { char** argv = NULL; int argc = 0; AllocArg(cmd, argc, argv); ExceptionInfo *exception = NULL; ImageInfo *image_info = NULL; MagickBooleanType status = MagickTrue; MagickCoreGenesis(*argv, MagickTrue); exception = AcquireExceptionInfo(); image_info = AcquireImageInfo(); status = MagickCommandGenesis(image_info, ConvertImageCommand, argc, argv, (char **) NULL, exception); image_info = DestroyImageInfo(image_info); exception = DestroyExceptionInfo(exception); MagickCoreTerminus(); FreeArg(argc, argv); return(status); } int main(int argc, char* argv[]) { IM_Convert("convert ( mf-small.jpg -colorspace gray -type grayscale -contrast-stretch 0 ) " "( -clone 0 -colorspace gray -negate -lat 25x25+10% -contrast-stretch 0 ) " "-compose copy_opacity -composite -fill white -opaque none +matte " "-deskew 40% -sharpen 0x1 mf-small-out.jpg"); }
all: g++ -o im -g `pkg-config --cflags --libs MagickWand` main.cpp clean: rm -f im
注意:
convert ( mf-small.jpg -colorspace gray -type grayscale -contrast-stretch 0 ) ( -clone 0 -colorspace gray -negate -lat 25x25+10% -contrast-stretch 0 ) -compose copy_opacity -composite -fill \"white\" -opaque none +matte -deskew 40% -sharpen 0x1 mf-small-out.jpg错误提示:
im: unable to open image `"white"': No such file or directory @ error/blob.c/OpenBlob/2641. im: no decode delegate for this image format `"white"' @ error/constitute.c/ReadImage/550.