From 292ade6625f2f3bed84afbe4d669613ebf3785f9 Mon Sep 17 00:00:00 2001 From: "reed@google.com" Date: Tue, 28 Jun 2011 20:54:03 +0000 Subject: add mac utility to turn a pdf into a bitmap git-svn-id: http://skia.googlecode.com/svn/trunk@1743 2bbb7eff-a529-9590-31e7-b0007b416f81 --- include/utils/mac/SkCGUtils.h | 3 ++ src/utils/mac/SkCreateCGImageRef.cpp | 65 ++++++++++++++++++++++++++++++++++++ 2 files changed, 68 insertions(+) diff --git a/include/utils/mac/SkCGUtils.h b/include/utils/mac/SkCGUtils.h index aba64679e3..4b3e341f4c 100644 --- a/include/utils/mac/SkCGUtils.h +++ b/include/utils/mac/SkCGUtils.h @@ -12,6 +12,7 @@ #endif class SkBitmap; +class SkStream; /** * Create an imageref from the specified bitmap using the specified colorspace. @@ -36,4 +37,6 @@ static inline CGImageRef SkCreateCGImageRef(const SkBitmap& bm) { */ void SkCGDrawBitmap(CGContextRef, const SkBitmap&, float x, float y); +bool SkPDFDocumentToBitmap(SkStream* stream, SkBitmap* output); + #endif diff --git a/src/utils/mac/SkCreateCGImageRef.cpp b/src/utils/mac/SkCreateCGImageRef.cpp index f4bda45c9a..ccc2199b14 100644 --- a/src/utils/mac/SkCreateCGImageRef.cpp +++ b/src/utils/mac/SkCreateCGImageRef.cpp @@ -125,5 +125,70 @@ void SkCGDrawBitmap(CGContextRef cg, const SkBitmap& bm, float x, float y) { } } +/////////////////////////////////////////////////////////////////////////////// +#include "SkStream.h" + +class SkAutoPDFRelease { +public: + SkAutoPDFRelease(CGPDFDocumentRef doc) : fDoc(doc) {} + ~SkAutoPDFRelease() { + if (fDoc) { + CGPDFDocumentRelease(fDoc); + } + } +private: + CGPDFDocumentRef fDoc; +}; + +static void CGDataProviderReleaseData_FromMalloc(void*, const void* data, + size_t size) { + sk_free((void*)data); +} + +bool SkPDFDocumentToBitmap(SkStream* stream, SkBitmap* output) { + size_t size = stream->getLength(); + void* ptr = sk_malloc_throw(size); + stream->read(ptr, size); + CGDataProviderRef data = CGDataProviderCreateWithData(NULL, ptr, size, + CGDataProviderReleaseData_FromMalloc); + if (NULL == data) { + return false; + } + + CGPDFDocumentRef pdf = CGPDFDocumentCreateWithProvider(data); + CGDataProviderRelease(data); + if (NULL == pdf) { + return false; + } + SkAutoPDFRelease releaseMe(pdf); + + CGPDFPageRef page = CGPDFDocumentGetPage(pdf, 1); + if (NULL == page) { + return false; + } + + CGRect bounds = CGPDFPageGetBoxRect(page, kCGPDFMediaBox); + + int w = (int)CGRectGetWidth(bounds); + int h = (int)CGRectGetHeight(bounds); + + SkBitmap bitmap; + bitmap.setConfig(SkBitmap::kARGB_8888_Config, w, h); + bitmap.allocPixels(); + bitmap.eraseColor(SK_ColorWHITE); + + CGBitmapInfo info = kCGBitmapByteOrder32Little | kCGImageAlphaPremultipliedFirst; + CGContextRef ctx = CGBitmapContextCreateWithData(bitmap.getPixels(), + w, h, 8, bitmap.rowBytes(), + CGColorSpaceCreateDeviceRGB(), + info, NULL, NULL); + if (ctx) { + CGContextDrawPDFPage(ctx, page); + CGContextRelease(ctx); + } + + output->swap(bitmap); + return true; +} -- cgit v1.2.3