我正在使用
this post中引用的代码,但是想切换到基于ImageMagick C-API的解决方案,因为我想在单个图像处理库上进行标准化,并且需要IM来完成其他任务.
我可以找到大量使用转换命令行工具的示例,但没有关于如何在代码中进行单色转换的示例.
那里有任何示例代码?
解决方法
您可以使用
MagickQuantizeImage功能实现单色转换,如
here所述.
我对抖动图像并不熟悉,但示例可能如下所示.
我对抖动图像并不熟悉,但示例可能如下所示.
#include <wand/MagickWand.h>
int main(int argc,char **argv)
{
const size_t number_colors = 2;
const size_t treedepth = 1;
MagickWandGenesis();
MagickWand *wand = NULL;
wand = NewMagickWand();
MagickReadImage(wand,"source.png");
MagickQuantizeImage(
wand,// MagickWand
number_colors,// Target number colors
GRAYColorspace,// Colorspace
treedepth,// Optimal depth
MagickTrue,// Dither
MagickFalse // Quantization error
);
MagickWriteImage(wand,"out.png");
if(wand)wand = DestroyMagickWand(wand);
MagickWandTerminus();
return 0;
}
这有时会给你一个相当斑点的图像.
调整深度,颜色编号和/或禁用抖动可能会使您的结果更接近您提供的示例所期望的结果.
MagickQuantizeImage(
wand,// MagickWand
number_colors,// Target number colors
GRAYColorspace,// Colorspace
treedepth,// Optimal depth
MagickFalse,// No-dither
MagickFalse // Quantization error
);
像这样……
对于iOS
将示例代码移植到iOS不需要太多努力. NextStep / Objective-c方法与MagickWand库兼容.以下示例使用临时文件来存储单色图像,但我确信有更好的方法将Magick图像数据直接传递给UImage对象.
// MyViewController.h
#import <UIKit/UIKit.h>
#import <wand/MagickWand.h>
@interface MyViewController : UIViewController
@property (retain,nonatomic) IBOutlet UIImageView *imageView;
@property (retain,nonatomic) MagickWand *wand;
@end
// MyViewController.m
#import "MyViewController.h"
@implementation MyViewController
- (void)viewDidLoad
{
[super viewDidLoad];
MagickWandGenesis();
self.wand = NewMagickWand();
[self drawMonochromeImage:@"logo:"];
}
-(void)drawMonochromeImage:(Nsstring *)filePath
{
// Create temporary file
Nsstring *tempFilePath = [NstemporaryDirectory()
stringByAppendingPathComponent:@"logo.jpg"];
// Read given image with C-string
MagickReadImage(self.wand,[filePath cStringUsingEncoding:NSASCIIStringEncoding]
);
// Monochrome image
MagickQuantizeImage(self.wand,2,GRAYColorspace,1,MagickFalse,MagickFalse);
// Write to temporary file
MagickWriteImage(self.wand,[tempFilePath cStringUsingEncoding:NSASCIIStringEncoding]
);
// Load UIImage from temporary file
UIImage *imgObj = [UIImage imageWithContentsOfFile:tempFilePath];
// display on device
[self.imageView setimage:imgObj];
[self.imageView setContentMode:UIViewContentModeScaleAspectFit];
}
-(void)viewDidUnload
{
// Clean-up
if (self.wand)
self.wand = DestroyMagickWand(self.wand);
MagickWandTerminus();
}
@end