GraphicsMagick.cc 17.9 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512

#include <cstring>

#include <v8.h>

#include <node.h>
#include <node_buffer.h>

#include <magick/api.h>

#define THROW_ERROR(TYPE, STR)                                          \
	return ThrowException(Exception::TYPE(String::New(STR)));

#define REQ_ARGS(N)                                                     \
  if (args.Length() < (N))                                              \
    return ThrowException(Exception::TypeError(                         \
                             String::New("Expected " #N "arguments"))); 

#define REQ_STR_ARG(I, VAR)                                             \
  if (args.Length() <= (I) || !args[I]->IsString())                     \
    return ThrowException(Exception::TypeError(                         \
                  String::New("Argument " #I " must be a string")));    \
  String::Utf8Value VAR(args[I]->ToString());

#define REQ_INT_ARG(I, VAR)                                             \
  int VAR;                                                              \
  if (args.Length() <= (I) || !args[I]->IsInt32())                      \
    return ThrowException(Exception::TypeError(                         \
                  String::New("Argument " #I " must be an integer")));  \
  VAR = args[I]->Int32Value();


#define REQ_IMG_ARG(I, VAR) \
if (args.Length() <= (I) || !args[I]->IsObject())                     \
    return ThrowException(Exception::TypeError(                         \
                  String::New("Argument " #I " must be an object")));   \
  Local<Object> _obj_ = Local<Object>::Cast(args[I]);                   \
  MagickImage *VAR = ObjectWrap::Unwrap<MagickImage>(_obj_);
                  
#define OPT_INT_ARG(I, VAR, DEFAULT)                                    \
  int VAR;                                                              \
  if (args.Length() <= (I)) {                                           \
    VAR = (DEFAULT);                                                    \
  } else if (args[I]->IsInt32()) {                                      \
    VAR = args[I]->Int32Value();                                        \
  } else {                                                              \
    return ThrowException(Exception::TypeError(                         \
              String::New("Argument " #I " must be an integer"))); \
  }

                  
#define REQ_RECT_ARG(I, VAR)                                            \
	REQ_INT_ARG(I+0, x)												\
	REQ_INT_ARG(I+1, y)											\
	REQ_INT_ARG(I+2, width)													\
	REQ_INT_ARG(I+3, height)													\
	RectangleInfo VAR = { width, height, x, y };

#define REQ_DOUBLE_ARG(I, VAR)                                          \
  double VAR;                                                           \
  if (args.Length() <= (I) || !args[I]->IsNumber())                     \
    return ThrowException(Exception::TypeError(                         \
                  String::New("Argument " #I " must be a number")));    \
  VAR = args[I]->NumberValue();

#define REQ_EXT_ARG(I, VAR)                                             \
  if (args.Length() <= (I) || !args[I]->IsExternal())                   \
    return ThrowException(Exception::TypeError(                         \
                  String::New("Argument " #I " invalid")));             \
  Local<External> VAR = Local<External>::Cast(args[I]);


#define OPT_INT_ARG(I, VAR, DEFAULT)                                    \
  int VAR;                                                              \
  if (args.Length() <= (I)) {                                           \
    VAR = (DEFAULT);                                                    \
  } else if (args[I]->IsInt32()) {                                      \
    VAR = args[I]->Int32Value();                                        \
  } else {                                                              \
    return ThrowException(Exception::TypeError(                         \
              String::New("Argument " #I " must be an integer"))); 		\
  }

#define OPT_DOUBLE_ARG(I, VAR, DEFAULT)                                    \
  int VAR;                                                              \
  if (args.Length() <= (I)) {                                           \
    VAR = (DEFAULT);                                                    \
  } else if (args[I]->IsNumber()) {                                      \
    VAR = args[I]->NumberValue();                                        \
  } else {                                                              \
    return ThrowException(Exception::TypeError(                         \
              String::New("Argument " #I " must be a number"))); 		\
  }

using namespace node;
using namespace v8;

/*
template <typename T> Handle<T> returnNewPointer(T ptr) {
	HandleScope scope;
	Local<Value> arg = External::New(ptr);
	Persistent<Object> obj(T::Constructor->GetFunction()->NewInstance(1, &arg));
	return scope.Close(obj);
}
*/


#define IMAGE_METHOD(apiname, apiargs...) \
		HandleScope scope; \
		Handle<Value> out; \
		ExceptionInfo exception; \
		Image *result; \
		MagickImage *image = ObjectWrap::Unwrap<MagickImage>(args.This()); \
		GetExceptionInfo(&exception); \
		result = apiname( *image, ##apiargs, &exception ); \
		if (result) { \
			Local<Object> object = constructorTemplate->GetFunction()->NewInstance(); \
			MagickImage *magickImage = ObjectWrap::Unwrap<MagickImage>(object); \
			magickImage->image = result; \
			out = scope.Close(object); \
		} else { \
			CatchException(&exception); \
			out = ThrowException(String::New("Unable to load image!")); \
		} \
		DestroyExceptionInfo(&exception); \
		return out;

class MagickImage : ObjectWrap {
public:
	
	static Persistent<FunctionTemplate> constructorTemplate;
	
	Image* image;
	
	
	
	MagickImage(Image* i) : ObjectWrap(), image(i) {
		
	}
	
	~MagickImage() {
		if (image != NULL)
			DestroyImage(image);
	}
	
	operator Image* () const {
		return image;
	}
	
	
	
	static void Init(Handle<Object> target) {
		
		
		Local<FunctionTemplate> t = FunctionTemplate::New(New);
		
		//Create a new persistent function template based around "create"; this
		//template is used as the prototype for making new instances of the object
		constructorTemplate = Persistent<FunctionTemplate>::New(t);
				
		//This object has one internal field (i.e. a field hidden from javascript);
		//This field is used to store a pointer to the image class
		constructorTemplate->InstanceTemplate()->SetInternalFieldCount(1);
		
		//Give the class a name
		constructorTemplate->SetClassName(String::NewSymbol("Image"));
		
		//All the methods for this class
		NODE_SET_PROTOTYPE_METHOD(t, "thumbnail", thumbnail);
		NODE_SET_PROTOTYPE_METHOD(t, "sample", sample);
		NODE_SET_PROTOTYPE_METHOD(t, "scale", scale);
		NODE_SET_PROTOTYPE_METHOD(t, "resize", resize);
		NODE_SET_PROTOTYPE_METHOD(t, "chop", chop);
		NODE_SET_PROTOTYPE_METHOD(t, "crop", crop);
		NODE_SET_PROTOTYPE_METHOD(t, "extent", extent);
		NODE_SET_PROTOTYPE_METHOD(t, "flip", flip);
		NODE_SET_PROTOTYPE_METHOD(t, "flop", flop);
		NODE_SET_PROTOTYPE_METHOD(t, "affineTransform", affineTransform);
		NODE_SET_PROTOTYPE_METHOD(t, "rotate", rotate);
		NODE_SET_PROTOTYPE_METHOD(t, "shear", shear);
		NODE_SET_PROTOTYPE_METHOD(t, "contrast", contrast);
		NODE_SET_PROTOTYPE_METHOD(t, "equalize", equalize);
		NODE_SET_PROTOTYPE_METHOD(t, "gamma", gamma);
		NODE_SET_PROTOTYPE_METHOD(t, "level", level);
		NODE_SET_PROTOTYPE_METHOD(t, "levelChannel", levelChannel);
		NODE_SET_PROTOTYPE_METHOD(t, "modulate", modulate);
		NODE_SET_PROTOTYPE_METHOD(t, "negate", negate);
		NODE_SET_PROTOTYPE_METHOD(t, "normalize", normalize);
		NODE_SET_PROTOTYPE_METHOD(t, "attribute", attribute);
		NODE_SET_PROTOTYPE_METHOD(t, "composite", composite);
		
		//Some getters
		t->PrototypeTemplate()->SetAccessor(String::NewSymbol("buffer"), getBuffer, NULL, Handle<Value>(), PROHIBITS_OVERWRITING, ReadOnly);
		t->PrototypeTemplate()->SetAccessor(String::NewSymbol("width"), getWidth, NULL, Handle<Value>(), PROHIBITS_OVERWRITING, ReadOnly);
		t->PrototypeTemplate()->SetAccessor(String::NewSymbol("height"), getHeight, NULL, Handle<Value>(), PROHIBITS_OVERWRITING, ReadOnly);
	}
	
	static Handle<Value> New(const Arguments &args) {
		HandleScope scope;
		MagickImage* magickImage = new MagickImage(NULL);
		magickImage->Wrap(args.This());
		return args.This();
	}
	
	
	static Handle<Value> getBuffer (Local<String> property, const AccessorInfo& info)
	{
		HandleScope scope;
		ExceptionInfo exception;
		size_t length;
		ImageInfo *imageInfo = CloneImageInfo(NULL);
		MagickImage *image = ObjectWrap::Unwrap<MagickImage>(info.This());
		GetExceptionInfo(&exception);
		void* data = ImageToBlob(imageInfo, *image, &length, &exception);
		if (data) {
			//http://sambro.is-super-awesome.com/2011/03/03/creating-a-proper-buffer-in-a-node-c-addon/
			Buffer *slowBuffer = Buffer::New(length);
			memcpy(Buffer::Data(slowBuffer), data, length);
			Local<Object> globalObj = Context::GetCurrent()->Global();
			Local<Function> bufferConstructor = Local<Function>::Cast(globalObj->Get(String::New("Buffer")));
			Handle<Value> constructorArgs[3] = { slowBuffer->handle_, Integer::New(length), Integer::New(0) };
			Local<Object> buffer =  bufferConstructor->NewInstance(3, constructorArgs);
			return scope.Close(buffer);
		} else {
			return ThrowException(String::New("Unable to convert image to blob!"));
		}
		
		
	}
	
	static Handle<Value> getWidth (Local<String> property, const AccessorInfo& info)
	{
		HandleScope scope;
		MagickImage* image = ObjectWrap::Unwrap<MagickImage>(info.This());
		Local<Number> result = Integer::New(image->image->columns);
		return scope.Close(result);
	}
	
	static Handle<Value> getHeight (Local<String> property, const AccessorInfo& info)
	{
		HandleScope scope;
		MagickImage* image = ObjectWrap::Unwrap<MagickImage>(info.This());
		Local<Number> result = Integer::New(image->image->rows);
		return scope.Close(result);
	}
	
	static Handle<Value> info(const Arguments &args) {
		
	}
	
	/**
	 * Create a new image from a buffer
	 */
	static Handle<Value> create(const Arguments &args) {
		
		HandleScope scope;
		
		if (args.Length() < 1) { 
			return Undefined();
		}
		
		Handle<Value> result;
		ExceptionInfo exception;
		const char* blob;
		size_t length;
		Image* image;
		ImageInfo *imageInfo = CloneImageInfo(NULL);
		
		GetExceptionInfo(&exception);
		
		if (args[0]->IsString()) {
			String::AsciiValue string(args[0]->ToString());
			length = string.length();
			blob = *string;
		} else if (Buffer::HasInstance(args[0])) {
			Local<Object> bufferIn=args[0]->ToObject();
			length = Buffer::Length(bufferIn);
			blob = Buffer::Data(bufferIn);
		}
		
		image = BlobToImage(imageInfo, blob, length, &exception);
		if (!image) {
			 CatchException(&exception);
			 result = ThrowException(String::New("Unable to load image!"));
		}
		else {
			Local<Object> object = constructorTemplate->GetFunction()->NewInstance();
			MagickImage *magickImage = ObjectWrap::Unwrap<MagickImage>(object);
			magickImage->image = image;
			result = scope.Close(object);
		}
		DestroyImageInfo(imageInfo);
    	DestroyExceptionInfo(&exception);
		return result;
	}
	
	static Handle<Value> thumbnail(const Arguments &args) {
		REQ_INT_ARG(0, width)
		REQ_INT_ARG(1, height)
		IMAGE_METHOD(ThumbnailImage, width, height)
	}
	
	static Handle<Value> sample(const Arguments &args) {
		REQ_INT_ARG(0, width)
		REQ_INT_ARG(1, height)
		IMAGE_METHOD(SampleImage, width, height)
	}
	
	static Handle<Value> scale(const Arguments &args) {
		REQ_INT_ARG(0, width)
		REQ_INT_ARG(1, height)
		IMAGE_METHOD(ScaleImage, width, height)
	}
	
	static Handle<Value> resize(const Arguments &args) {
		REQ_INT_ARG(0, width)
		REQ_INT_ARG(1, height)
		OPT_INT_ARG(2, f, LanczosFilter)
		OPT_DOUBLE_ARG(3, blur, 1.0)
		FilterTypes filter = FilterTypes(f);
		IMAGE_METHOD(ResizeImage, width, height, filter, blur)
		
	}
	
	//http://www.graphicsmagick.org/api/transform.html#chopimage
	static Handle<Value> chop(const Arguments &args) {
		REQ_RECT_ARG(0, chopInfo)
		IMAGE_METHOD(ChopImage, &chopInfo)
	}
	
	//http://www.graphicsmagick.org/api/transform.html#cropimage
	static Handle<Value> crop(const Arguments &args) {
		REQ_RECT_ARG(0, cropInfo)
		IMAGE_METHOD(CropImage, &cropInfo)
	}
	
	//http://www.graphicsmagick.org/api/transform.html#extentimage
	static Handle<Value> extent(const Arguments &args) {
		REQ_RECT_ARG(0, geometry)
		IMAGE_METHOD(ExtentImage, &geometry)
	}
	
	static Handle<Value> flip(const Arguments &args) {
		IMAGE_METHOD(FlipImage)
	}
	
	static Handle<Value> flop(const Arguments &args) {
		IMAGE_METHOD(FlopImage)
	}
	
	//http://www.graphicsmagick.org/api/shear.html#affinetransformimage
	static Handle<Value> affineTransform(const Arguments &args) {
		AffineMatrix affineMatrix;
		IMAGE_METHOD(AffineTransformImage, &affineMatrix)
	}
	
	//http://www.graphicsmagick.org/api/shear.html#rotateimage
	static Handle<Value> rotate(const Arguments &args) {
		REQ_DOUBLE_ARG(0, degrees)
		IMAGE_METHOD(RotateImage, degrees)
	}
	
	//http://www.graphicsmagick.org/api/shear.html#shearimage
	static Handle<Value> shear(const Arguments &args) {
		REQ_DOUBLE_ARG(0, x)
		REQ_DOUBLE_ARG(1, y)
		IMAGE_METHOD(ShearImage, x, y)
	}
	
	//http://www.graphicsmagick.org/api/enhance.html#contrastimage
	static Handle<Value> contrast(const Arguments &args) {
		REQ_INT_ARG(0, s)
		//IMAGE_METHOD(ContrastImage, s)
		return Undefined();
	}
	
	//http://www.graphicsmagick.org/api/enhance.html#equalizeimage
	static Handle<Value> equalize(const Arguments &args) {
		//IMAGE_METHOD(EqualizeImage)
		return Undefined();
	}
	
	static Handle<Value> gamma(const Arguments &args) {
		//IMAGE_METHOD(GammaImage)
		return Undefined();
	}
	
	static Handle<Value> level(const Arguments &args) {
		//IMAGE_METHOD(LevelImage)
		return Undefined();
	}
	
	static Handle<Value> levelChannel(const Arguments &args) {
		//IMAGE_METHOD(LevelImageChannel)
		return Undefined();
	}
	
	static Handle<Value> modulate(const Arguments &args) {
		//IMAGE_METHOD(ModulateImage)
		return Undefined();
	}
	
	static Handle<Value> negate(const Arguments &args) {
		//IMAGE_METHOD(NegateImage)
		return Undefined();
	}
	
	static Handle<Value> normalize(const Arguments &args) {
		//IMAGE_METHOD(NormalizeImage)
		return Undefined();
	}
	
	//http://www.graphicsmagick.org/api/attribute.html#getimageattribute
	//http://www.graphicsmagick.org/api/attribute.html#setimageattribute
	static Handle<Value> attribute(const Arguments &args) {
		//MagickImage *image = ObjectWrap::Unwrap<MagickImage>(args.This());
		//ExceptionInfo exception;
		return Undefined();
	}
	
	//http://www.graphicsmagick.org/api/composite.html
	static Handle<Value> composite(const Arguments &args) {
		HandleScope scope;
		Handle<Value> out;
		CompositeOperator compose;
		MagickImage *image = ObjectWrap::Unwrap<MagickImage>(args.This());
		REQ_IMG_ARG(0, i)
		REQ_INT_ARG(1, c)
		OPT_INT_ARG(2, x, 0)
		OPT_INT_ARG(3, y, 0)
		const Image* compositeImage = *i;
		compose = CompositeOperator(c);
		if (CompositeImage( *image, compose, compositeImage, x, y ) == MagickPass) 
			return args.This();
		else 
			return ThrowException(String::New("Unable to composite image!"));

	}
	
};

Persistent<FunctionTemplate> MagickImage::constructorTemplate;

extern "C" {
	static void init (Handle<Object> target)
	{
		InitializeMagick(NULL);
		
		
		//http://www.graphicsmagick.org/api/types.html#filtertypes
		NODE_DEFINE_CONSTANT(target, UndefinedFilter);
		NODE_DEFINE_CONSTANT(target, PointFilter);
		NODE_DEFINE_CONSTANT(target, BoxFilter);
		NODE_DEFINE_CONSTANT(target, TriangleFilter);
		NODE_DEFINE_CONSTANT(target, HermiteFilter);
		NODE_DEFINE_CONSTANT(target, HanningFilter);
		NODE_DEFINE_CONSTANT(target, HammingFilter);
		NODE_DEFINE_CONSTANT(target, BlackmanFilter);
		NODE_DEFINE_CONSTANT(target, GaussianFilter);
		NODE_DEFINE_CONSTANT(target, QuadraticFilter);
		NODE_DEFINE_CONSTANT(target, CubicFilter);
		NODE_DEFINE_CONSTANT(target, CatromFilter);
		NODE_DEFINE_CONSTANT(target, MitchellFilter);
		NODE_DEFINE_CONSTANT(target, LanczosFilter);
		NODE_DEFINE_CONSTANT(target, BesselFilter);
		NODE_DEFINE_CONSTANT(target, SincFilter);
		
		//http://www.graphicsmagick.org/api/types.html#compositeoperator
		NODE_DEFINE_CONSTANT(target, UndefinedCompositeOp);
		NODE_DEFINE_CONSTANT(target, OverCompositeOp);
		NODE_DEFINE_CONSTANT(target, InCompositeOp);
		NODE_DEFINE_CONSTANT(target, OutCompositeOp);
		NODE_DEFINE_CONSTANT(target, AtopCompositeOp);
		NODE_DEFINE_CONSTANT(target, XorCompositeOp);
		NODE_DEFINE_CONSTANT(target, PlusCompositeOp);
		NODE_DEFINE_CONSTANT(target, MinusCompositeOp);
		NODE_DEFINE_CONSTANT(target, AddCompositeOp);
		NODE_DEFINE_CONSTANT(target, SubtractCompositeOp);
		NODE_DEFINE_CONSTANT(target, DifferenceCompositeOp);
		NODE_DEFINE_CONSTANT(target, BumpmapCompositeOp);
		NODE_DEFINE_CONSTANT(target, CopyCompositeOp);
		NODE_DEFINE_CONSTANT(target, CopyRedCompositeOp);
		NODE_DEFINE_CONSTANT(target, CopyGreenCompositeOp);
		NODE_DEFINE_CONSTANT(target, CopyBlueCompositeOp);
		NODE_DEFINE_CONSTANT(target, CopyOpacityCompositeOp);
		NODE_DEFINE_CONSTANT(target, ClearCompositeOp);
		NODE_DEFINE_CONSTANT(target, DissolveCompositeOp);
		NODE_DEFINE_CONSTANT(target, DisplaceCompositeOp);
		NODE_DEFINE_CONSTANT(target, ModulateCompositeOp);
		NODE_DEFINE_CONSTANT(target, ThresholdCompositeOp);
		NODE_DEFINE_CONSTANT(target, NoCompositeOp);
		NODE_DEFINE_CONSTANT(target, DarkenCompositeOp);
		NODE_DEFINE_CONSTANT(target, LightenCompositeOp);
		NODE_DEFINE_CONSTANT(target, HueCompositeOp);
		NODE_DEFINE_CONSTANT(target, SaturateCompositeOp);
		NODE_DEFINE_CONSTANT(target, ColorizeCompositeOp);
		NODE_DEFINE_CONSTANT(target, LuminizeCompositeOp);
		NODE_DEFINE_CONSTANT(target, ScreenCompositeOp);
		NODE_DEFINE_CONSTANT(target, OverlayCompositeOp);
		NODE_DEFINE_CONSTANT(target, CopyCyanCompositeOp);
		NODE_DEFINE_CONSTANT(target, CopyMagentaCompositeOp);
		NODE_DEFINE_CONSTANT(target, CopyYellowCompositeOp);
		NODE_DEFINE_CONSTANT(target, CopyBlackCompositeOp);
		NODE_DEFINE_CONSTANT(target, DivideCompositeOp);
		
		NODE_SET_METHOD(target, "image", MagickImage::create);
		
		MagickImage::Init(target);
	}

	NODE_MODULE(GraphicsMagick, init)
}