Skip to content

Instantly share code, notes, and snippets.

@SharkyRawr
Created February 3, 2020 23:14
Show Gist options
  • Save SharkyRawr/f4de1c2b6cdc44d511e657027fd7ca72 to your computer and use it in GitHub Desktop.
Save SharkyRawr/f4de1c2b6cdc44d511e657027fd7ca72 to your computer and use it in GitHub Desktop.
// This is the main DLL file.
#include "stdafx.h"
array<Byte>^ WebPCLR::Encoder::Encode(Bitmap^ bmp, float quality) {
Rectangle bounds = Rectangle(0, 0, bmp->Width, bmp->Height);
Imaging::BitmapData^ bmpdata = bmp->LockBits(bounds, Imaging::ImageLockMode::ReadOnly, Imaging::PixelFormat::Format32bppArgb);
IntPtr argb = bmpdata->Scan0;
WebPConfig cfg;
WebPConfigPreset(&cfg, WEBP_PRESET_DEFAULT, quality);
//WebPConfigInit(&cfg);
cfg.method = 6;
if (WebPValidateConfig(&cfg) == false) {
throw gcnew System::Exception("WebP config validation failed (invalid quality?)");
}
WebPPicture webp;
if (WebPPictureInit(&webp) == false) {
throw gcnew Exception("Unable to initialize WebPPicture data structure (version mismatch?)");
}
webp.width = bmp->Width;
webp.height = bmp->Height;
webp.use_argb = true;
if (WebPPictureAlloc(&webp) == false) {
throw gcnew Exception("Unable to allocate memory: WebPPictureAlloc() returned FALSE)");
}
// Copy RGBA bitmap data
//WebPPictureImportRGBA(&webp, (uint8_t*)((void*)argb), bmpdata->Stride);
webp.argb = (uint32_t*)((void*)argb);
webp.argb_stride = bmpdata->Stride / sizeof(uint32_t); // Convert BitmapData stride (bytes) to webp (pixels)
WebPMemoryWriter writer;
WebPMemoryWriterInit(&writer);
webp.writer = WebPMemoryWrite;
webp.custom_ptr = &writer;
int status = WebPEncode(&cfg, &webp);
WebPPictureFree(&webp);
bmp->UnlockBits(bmpdata);
if (!status) {
throw gcnew Exception(String::Format("WebPEncode error, code: {0}", (int)webp.error_code));
}
array<Byte>^ buf = gcnew array<Byte>(writer.size);
System::Runtime::InteropServices::Marshal::Copy(IntPtr(writer.mem), buf, 0, writer.size);
return buf;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment