2021-04-24 22:54:47 +00:00
|
|
|
#include <Magick++.h>
|
2020-07-20 22:10:04 +00:00
|
|
|
#include <napi.h>
|
2021-04-24 22:54:47 +00:00
|
|
|
|
2020-08-28 02:34:12 +00:00
|
|
|
#include <list>
|
2020-07-20 22:10:04 +00:00
|
|
|
|
|
|
|
using namespace std;
|
|
|
|
using namespace Magick;
|
|
|
|
|
2021-04-24 22:54:47 +00:00
|
|
|
Napi::Value Jpeg(const Napi::CallbackInfo &info) {
|
2020-07-20 22:10:04 +00:00
|
|
|
Napi::Env env = info.Env();
|
|
|
|
|
2021-04-26 14:47:03 +00:00
|
|
|
try {
|
|
|
|
Napi::Object obj = info[0].As<Napi::Object>();
|
2021-05-11 19:25:02 +00:00
|
|
|
Napi::Buffer<char> data = obj.Get("data").As<Napi::Buffer<char>>();
|
2021-06-29 22:26:22 +00:00
|
|
|
string type = obj.Get("type").As<Napi::String>().Utf8Value();
|
|
|
|
int delay =
|
|
|
|
obj.Has("delay") ? obj.Get("delay").As<Napi::Number>().Int32Value() : 0;
|
2020-07-20 22:10:04 +00:00
|
|
|
|
2021-04-26 14:47:03 +00:00
|
|
|
Blob blob;
|
2021-04-24 22:54:47 +00:00
|
|
|
|
2021-04-26 14:47:03 +00:00
|
|
|
Napi::Object result = Napi::Object::New(env);
|
2021-06-29 22:26:22 +00:00
|
|
|
|
|
|
|
if (type == "gif") {
|
|
|
|
list<Image> frames;
|
|
|
|
list<Image> coalesced;
|
|
|
|
list<Image> jpeged;
|
|
|
|
readImages(&frames, Blob(data.Data(), data.Length()));
|
|
|
|
coalesceImages(&coalesced, frames.begin(), frames.end());
|
|
|
|
|
|
|
|
for (Image &image : coalesced) {
|
|
|
|
Blob temp;
|
|
|
|
image.quality(1);
|
|
|
|
image.magick("JPEG");
|
|
|
|
image.write(&temp);
|
|
|
|
Image newImage(temp);
|
|
|
|
newImage.magick(type);
|
|
|
|
newImage.animationDelay(delay == 0 ? image.animationDelay() : delay);
|
|
|
|
jpeged.push_back(newImage);
|
|
|
|
}
|
|
|
|
|
|
|
|
optimizeTransparency(jpeged.begin(), jpeged.end());
|
|
|
|
|
|
|
|
for (Image &image : jpeged) {
|
|
|
|
image.quantizeDither(false);
|
|
|
|
image.quantize();
|
|
|
|
}
|
|
|
|
|
|
|
|
writeImages(jpeged.begin(), jpeged.end(), &blob);
|
|
|
|
|
|
|
|
result.Set("data", Napi::Buffer<char>::Copy(env, (char *)blob.data(),
|
|
|
|
blob.length()));
|
|
|
|
result.Set("type", type);
|
|
|
|
} else {
|
|
|
|
Image image;
|
|
|
|
image.read(Blob(data.Data(), data.Length()));
|
|
|
|
image.quality(1);
|
|
|
|
image.magick("JPEG");
|
|
|
|
image.write(&blob);
|
|
|
|
|
|
|
|
result.Set("data", Napi::Buffer<char>::Copy(env, (char *)blob.data(),
|
|
|
|
blob.length()));
|
|
|
|
result.Set("type", "jpg");
|
|
|
|
}
|
|
|
|
|
2021-04-26 14:47:03 +00:00
|
|
|
return result;
|
|
|
|
} catch (std::exception const &err) {
|
|
|
|
throw Napi::Error::New(env, err.what());
|
2021-05-03 21:01:48 +00:00
|
|
|
} catch (...) {
|
|
|
|
throw Napi::Error::New(env, "Unknown error");
|
2021-04-26 14:47:03 +00:00
|
|
|
}
|
2020-07-20 22:10:04 +00:00
|
|
|
}
|