[CG] Separate image encoding from dataURL construction
[WebKit-https.git] / Source / WebCore / platform / graphics / cg / ImageBufferCG.cpp
1 /*
2  * Copyright (C) 2006 Nikolas Zimmermann <zimmermann@kde.org>
3  * Copyright (C) 2008 Apple Inc. All rights reserved.
4  * Copyright (C) 2010 Torch Mobile (Beijing) Co. Ltd. All rights reserved.
5  *
6  * Redistribution and use in source and binary forms, with or without
7  * modification, are permitted provided that the following conditions
8  * are met:
9  * 1. Redistributions of source code must retain the above copyright
10  *    notice, this list of conditions and the following disclaimer.
11  * 2. Redistributions in binary form must reproduce the above copyright
12  *    notice, this list of conditions and the following disclaimer in the
13  *    documentation and/or other materials provided with the distribution.
14  *
15  * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
16  * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
17  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
18  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL APPLE COMPUTER, INC. OR
19  * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
20  * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
21  * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
22  * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
23  * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
24  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
25  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
26  */
27
28 #include "config.h"
29 #include "ImageBuffer.h"
30
31 #include "Base64.h"
32 #include "BitmapImage.h"
33 #include "GraphicsContext.h"
34 #include "GraphicsContextCG.h"
35 #include "ImageData.h"
36 #include "MIMETypeRegistry.h"
37 #include <ApplicationServices/ApplicationServices.h>
38 #include <math.h>
39 #include <wtf/Assertions.h>
40 #include <wtf/CheckedArithmetic.h>
41 #include <wtf/MainThread.h>
42 #include <wtf/OwnArrayPtr.h>
43 #include <wtf/RetainPtr.h>
44 #include <wtf/UnusedParam.h>
45 #include <wtf/text/WTFString.h>
46
47 #if PLATFORM(MAC) || PLATFORM(CHROMIUM)
48 #include "WebCoreSystemInterface.h"
49 #endif
50
51 #if USE(IOSURFACE_CANVAS_BACKING_STORE)
52 #include <IOSurface/IOSurface.h>
53 #endif
54
55 #if defined(BUILDING_ON_LION)
56 #include <wtf/CurrentTime.h>
57 #endif
58
59 using namespace std;
60
61 namespace WebCore {
62
63 #if USE(IOSURFACE_CANVAS_BACKING_STORE)
64 static const int maxIOSurfaceDimension = 4096;
65 static const int minIOSurfaceArea = 50 * 100;
66
67 static RetainPtr<IOSurfaceRef> createIOSurface(const IntSize& size)
68 {
69     unsigned pixelFormat = 'BGRA';
70     unsigned bytesPerElement = 4;
71     int width = size.width();
72     int height = size.height();
73
74     unsigned long bytesPerRow = IOSurfaceAlignProperty(kIOSurfaceBytesPerRow, size.width() * bytesPerElement);
75     if (!bytesPerRow)
76         return 0;
77
78     unsigned long allocSize = IOSurfaceAlignProperty(kIOSurfaceAllocSize, size.height() * bytesPerRow);
79     if (!allocSize)
80         return 0;
81
82     const void *keys[6];
83     const void *values[6];
84     keys[0] = kIOSurfaceWidth;
85     values[0] = CFNumberCreate(0, kCFNumberIntType, &width);
86     keys[1] = kIOSurfaceHeight;
87     values[1] = CFNumberCreate(0, kCFNumberIntType, &height);
88     keys[2] = kIOSurfacePixelFormat;
89     values[2] = CFNumberCreate(0, kCFNumberIntType, &pixelFormat);
90     keys[3] = kIOSurfaceBytesPerElement;
91     values[3] = CFNumberCreate(0, kCFNumberIntType, &bytesPerElement);
92     keys[4] = kIOSurfaceBytesPerRow;
93     values[4] = CFNumberCreate(0, kCFNumberLongType, &bytesPerRow);
94     keys[5] = kIOSurfaceAllocSize;
95     values[5] = CFNumberCreate(0, kCFNumberLongType, &allocSize);
96
97     RetainPtr<CFDictionaryRef> dict(AdoptCF, CFDictionaryCreate(0, keys, values, 6, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks));
98     for (unsigned i = 0; i < 6; i++)
99         CFRelease(values[i]);
100
101     return RetainPtr<IOSurfaceRef>(AdoptCF, IOSurfaceCreate(dict.get()));
102 }
103 #endif
104
105 static void releaseImageData(void*, const void* data, size_t)
106 {
107     fastFree(const_cast<void*>(data));
108 }
109
110 ImageBuffer::ImageBuffer(const IntSize& size, float resolutionScale, ColorSpace imageColorSpace, RenderingMode renderingMode, DeferralMode, bool& success)
111     : m_data(size) // NOTE: The input here isn't important as ImageBufferDataCG's constructor just ignores it.
112     , m_logicalSize(size)
113     , m_resolutionScale(resolutionScale)
114 {
115     float scaledWidth = ceilf(resolutionScale * size.width());
116     float scaledHeight = ceilf(resolutionScale * size.height());
117
118     // FIXME: Should we automatically use a lower resolution?
119     if (!FloatSize(scaledWidth, scaledHeight).isExpressibleAsIntSize())
120         return;
121
122     m_size = IntSize(scaledWidth, scaledHeight);
123
124     success = false;  // Make early return mean failure.
125     bool accelerateRendering = renderingMode == Accelerated;
126     if (m_size.width() <= 0 || m_size.height() <= 0)
127         return;
128
129     Checked<int, RecordOverflow> width = m_size.width();
130     Checked<int, RecordOverflow> height = m_size.height();
131
132     // Prevent integer overflows
133     m_data.m_bytesPerRow = 4 * width;
134     Checked<size_t, RecordOverflow> numBytes = height * m_data.m_bytesPerRow;
135     if (numBytes.hasOverflowed())
136         return;
137
138 #if USE(IOSURFACE_CANVAS_BACKING_STORE)
139     if (width.unsafeGet() >= maxIOSurfaceDimension || height.unsafeGet() >= maxIOSurfaceDimension || (width * height).unsafeGet() < minIOSurfaceArea)
140         accelerateRendering = false;
141 #else
142     ASSERT(renderingMode == Unaccelerated);
143 #endif
144
145     switch (imageColorSpace) {
146     case ColorSpaceDeviceRGB:
147         m_data.m_colorSpace = deviceRGBColorSpaceRef();
148         break;
149     case ColorSpaceSRGB:
150         m_data.m_colorSpace = sRGBColorSpaceRef();
151         break;
152     case ColorSpaceLinearRGB:
153         m_data.m_colorSpace = linearRGBColorSpaceRef();
154         break;
155     }
156
157     RetainPtr<CGContextRef> cgContext;
158     if (accelerateRendering) {
159 #if USE(IOSURFACE_CANVAS_BACKING_STORE)
160         m_data.m_surface = createIOSurface(m_size);
161         cgContext.adoptCF(wkIOSurfaceContextCreate(m_data.m_surface.get(), width.unsafeGet(), height.unsafeGet(), m_data.m_colorSpace));
162 #endif
163         if (!cgContext)
164             accelerateRendering = false; // If allocation fails, fall back to non-accelerated path.
165     }
166
167     if (!accelerateRendering) {
168         if (!tryFastCalloc(height.unsafeGet(), m_data.m_bytesPerRow.unsafeGet()).getValue(m_data.m_data))
169             return;
170         ASSERT(!(reinterpret_cast<size_t>(m_data.m_data) & 2));
171
172         m_data.m_bitmapInfo = kCGImageAlphaPremultipliedLast;
173         cgContext.adoptCF(CGBitmapContextCreate(m_data.m_data, width.unsafeGet(), height.unsafeGet(), 8, m_data.m_bytesPerRow.unsafeGet(), m_data.m_colorSpace, m_data.m_bitmapInfo));
174         // Create a live image that wraps the data.
175         m_data.m_dataProvider.adoptCF(CGDataProviderCreateWithData(0, m_data.m_data, numBytes.unsafeGet(), releaseImageData));
176     }
177
178     if (!cgContext)
179         return;
180
181     m_context = adoptPtr(new GraphicsContext(cgContext.get()));
182     m_context->applyDeviceScaleFactor(m_resolutionScale);
183     m_context->scale(FloatSize(1, -1));
184     m_context->translate(0, -size.height());
185     m_context->setIsAcceleratedContext(accelerateRendering);
186 #if defined(BUILDING_ON_LION)
187     m_data.m_lastFlushTime = currentTimeMS();
188 #endif
189     success = true;
190 }
191
192 ImageBuffer::~ImageBuffer()
193 {
194 }
195
196 GraphicsContext* ImageBuffer::context() const
197 {
198 #if defined(BUILDING_ON_LION)
199     // Force a flush if last flush was more than 20ms ago
200     if (m_context->isAcceleratedContext()) {
201         double elapsedTime = currentTimeMS() - m_data.m_lastFlushTime;
202         double maxFlushInterval = 20; // in ms
203
204         if (elapsedTime > maxFlushInterval) {
205             CGContextRef context = m_context->platformContext();
206             CGContextFlush(context);
207             m_data.m_lastFlushTime = currentTimeMS();
208         }
209     }
210 #endif
211
212     return m_context.get();
213 }
214
215 PassRefPtr<Image> ImageBuffer::copyImage(BackingStoreCopy copyBehavior) const
216 {
217     RetainPtr<CGImageRef> image;
218     if (m_resolutionScale == 1)
219         image = copyNativeImage(copyBehavior);
220     else {
221         image.adoptCF(copyNativeImage(DontCopyBackingStore));
222         RetainPtr<CGContextRef> context(AdoptCF, CGBitmapContextCreate(0, logicalSize().width(), logicalSize().height(), 8, 4 * logicalSize().width(), deviceRGBColorSpaceRef(), kCGImageAlphaPremultipliedLast));
223         CGContextSetBlendMode(context.get(), kCGBlendModeCopy);
224         CGContextDrawImage(context.get(), CGRectMake(0, 0, logicalSize().width(), logicalSize().height()), image.get());
225         image = CGBitmapContextCreateImage(context.get());
226     }
227
228     if (!image)
229         return 0;
230
231     return BitmapImage::create(image.get());
232 }
233
234 NativeImagePtr ImageBuffer::copyNativeImage(BackingStoreCopy copyBehavior) const
235 {
236     CGImageRef image = 0;
237     if (!m_context->isAcceleratedContext()) {
238         switch (copyBehavior) {
239         case DontCopyBackingStore:
240             image = CGImageCreate(internalSize().width(), internalSize().height(), 8, 32, m_data.m_bytesPerRow.unsafeGet(), m_data.m_colorSpace, m_data.m_bitmapInfo, m_data.m_dataProvider.get(), 0, true, kCGRenderingIntentDefault);
241             break;
242         case CopyBackingStore:
243             image = CGBitmapContextCreateImage(context()->platformContext());
244             break;
245         default:
246             ASSERT_NOT_REACHED();
247             break;
248         }
249     }
250 #if USE(IOSURFACE_CANVAS_BACKING_STORE)
251     else {
252         image = wkIOSurfaceContextCreateImage(context()->platformContext());
253 #if defined(BUILDING_ON_LION)
254         m_data.m_lastFlushTime = currentTimeMS();
255 #endif
256     }
257 #endif
258
259     return image;
260 }
261
262 void ImageBuffer::draw(GraphicsContext* destContext, ColorSpace styleColorSpace, const FloatRect& destRect, const FloatRect& srcRect, CompositeOperator op, bool useLowQualityScale)
263 {
264     UNUSED_PARAM(useLowQualityScale);
265     ColorSpace colorSpace = (destContext == m_context) ? ColorSpaceDeviceRGB : styleColorSpace;
266
267     RetainPtr<CGImageRef> image;
268     if (destContext == m_context || destContext->isAcceleratedContext())
269         image.adoptCF(copyNativeImage(CopyBackingStore)); // Drawing into our own buffer, need to deep copy.
270     else
271         image.adoptCF(copyNativeImage(DontCopyBackingStore));
272
273     FloatRect adjustedSrcRect = srcRect;
274     adjustedSrcRect.scale(m_resolutionScale, m_resolutionScale);
275     destContext->drawNativeImage(image.get(), internalSize(), colorSpace, destRect, adjustedSrcRect, op);
276 }
277
278 void ImageBuffer::drawPattern(GraphicsContext* destContext, const FloatRect& srcRect, const AffineTransform& patternTransform, const FloatPoint& phase, ColorSpace styleColorSpace, CompositeOperator op, const FloatRect& destRect)
279 {
280     FloatRect adjustedSrcRect = srcRect;
281     adjustedSrcRect.scale(m_resolutionScale, m_resolutionScale);
282
283     if (!m_context->isAcceleratedContext()) {
284         if (destContext == m_context || destContext->isAcceleratedContext()) {
285             RefPtr<Image> copy = copyImage(CopyBackingStore); // Drawing into our own buffer, need to deep copy.
286             copy->drawPattern(destContext, adjustedSrcRect, patternTransform, phase, styleColorSpace, op, destRect);
287         } else {
288             RefPtr<Image> imageForRendering = copyImage(DontCopyBackingStore);
289             imageForRendering->drawPattern(destContext, adjustedSrcRect, patternTransform, phase, styleColorSpace, op, destRect);
290         }
291     } else {
292         RefPtr<Image> copy = copyImage(CopyBackingStore);
293         copy->drawPattern(destContext, adjustedSrcRect, patternTransform, phase, styleColorSpace, op, destRect);
294     }
295 }
296
297 void ImageBuffer::clip(GraphicsContext* contextToClip, const FloatRect& rect) const
298 {
299     CGContextRef platformContextToClip = contextToClip->platformContext();
300     // FIXME: This image needs to be grayscale to be used as an alpha mask here.
301     RetainPtr<CGImageRef> image(AdoptCF, copyNativeImage(DontCopyBackingStore));
302     CGContextTranslateCTM(platformContextToClip, rect.x(), rect.y() + rect.height());
303     CGContextScaleCTM(platformContextToClip, 1, -1);
304     CGContextClipToMask(platformContextToClip, FloatRect(FloatPoint(), rect.size()), image.get());
305     CGContextScaleCTM(platformContextToClip, 1, -1);
306     CGContextTranslateCTM(platformContextToClip, -rect.x(), -rect.y() - rect.height());
307 }
308
309 PassRefPtr<Uint8ClampedArray> ImageBuffer::getUnmultipliedImageData(const IntRect& rect, CoordinateSystem coordinateSystem) const
310 {
311     if (m_context->isAcceleratedContext()) {
312         CGContextFlush(context()->platformContext());
313 #if defined(BUILDING_ON_LION)
314         m_data.m_lastFlushTime = currentTimeMS();
315 #endif
316     }
317     return m_data.getData(rect, internalSize(), m_context->isAcceleratedContext(), true, coordinateSystem == LogicalCoordinateSystem ? m_resolutionScale : 1);
318 }
319
320 PassRefPtr<Uint8ClampedArray> ImageBuffer::getPremultipliedImageData(const IntRect& rect, CoordinateSystem coordinateSystem) const
321 {
322     if (m_context->isAcceleratedContext()) {
323         CGContextFlush(context()->platformContext());
324 #if defined(BUILDING_ON_LION)
325         m_data.m_lastFlushTime = currentTimeMS();
326 #endif
327     }
328     return m_data.getData(rect, internalSize(), m_context->isAcceleratedContext(), false, coordinateSystem == LogicalCoordinateSystem ? m_resolutionScale : 1);
329 }
330
331 void ImageBuffer::putByteArray(Multiply multiplied, Uint8ClampedArray* source, const IntSize& sourceSize, const IntRect& sourceRect, const IntPoint& destPoint, CoordinateSystem coordinateSystem)
332 {
333     if (!m_context->isAcceleratedContext()) {
334         m_data.putData(source, sourceSize, sourceRect, destPoint, internalSize(), m_context->isAcceleratedContext(), multiplied == Unmultiplied, coordinateSystem == LogicalCoordinateSystem ? m_resolutionScale : 1);
335         return;
336     }
337
338 #if USE(IOSURFACE_CANVAS_BACKING_STORE)
339     // Make a copy of the source to ensure the bits don't change before being drawn
340     IntSize sourceCopySize(sourceRect.width(), sourceRect.height());
341     OwnPtr<ImageBuffer> sourceCopy = ImageBuffer::create(sourceCopySize, 1, ColorSpaceDeviceRGB, Unaccelerated);
342     if (!sourceCopy)
343         return;
344
345     sourceCopy->m_data.putData(source, sourceSize, sourceRect, IntPoint(-sourceRect.x(), -sourceRect.y()), sourceCopy->internalSize(), sourceCopy->context()->isAcceleratedContext(), multiplied == Unmultiplied, 1);
346
347     // Set up context for using drawImage as a direct bit copy
348     CGContextRef destContext = context()->platformContext();
349     CGContextSaveGState(destContext);
350     if (coordinateSystem == LogicalCoordinateSystem)
351         CGContextConcatCTM(destContext, AffineTransform(wkGetUserToBaseCTM(destContext)).inverse());
352     else
353         CGContextConcatCTM(destContext, AffineTransform(CGContextGetCTM(destContext)).inverse());
354     wkCGContextResetClip(destContext);
355     CGContextSetInterpolationQuality(destContext, kCGInterpolationNone);
356     CGContextSetAlpha(destContext, 1.0);
357     CGContextSetBlendMode(destContext, kCGBlendModeCopy);
358     CGContextSetShadowWithColor(destContext, CGSizeZero, 0, 0);
359
360     // Draw the image in CG coordinate space
361     IntPoint destPointInCGCoords(destPoint.x() + sourceRect.x(), (coordinateSystem == LogicalCoordinateSystem ? logicalSize() : internalSize()).height() - (destPoint.y() + sourceRect.y()) - sourceRect.height());
362     IntRect destRectInCGCoords(destPointInCGCoords, sourceCopySize);
363     RetainPtr<CGImageRef> sourceCopyImage(AdoptCF, sourceCopy->copyNativeImage());
364     CGContextDrawImage(destContext, destRectInCGCoords, sourceCopyImage.get());
365     CGContextRestoreGState(destContext);
366 #endif
367 }
368
369 static inline CFStringRef jpegUTI()
370 {
371 #if PLATFORM(WIN)
372     static const CFStringRef kUTTypeJPEG = CFSTR("public.jpeg");
373 #endif
374     return kUTTypeJPEG;
375 }
376     
377 static RetainPtr<CFStringRef> utiFromMIMEType(const String& mimeType)
378 {
379 #if PLATFORM(MAC)
380     RetainPtr<CFStringRef> mimeTypeCFString(AdoptCF, mimeType.createCFString());
381     return RetainPtr<CFStringRef>(AdoptCF, UTTypeCreatePreferredIdentifierForTag(kUTTagClassMIMEType, mimeTypeCFString.get(), 0));
382 #else
383     ASSERT(isMainThread()); // It is unclear if CFSTR is threadsafe.
384
385     // FIXME: Add Windows support for all the supported UTIs when a way to convert from MIMEType to UTI reliably is found.
386     // For now, only support PNG, JPEG, and GIF. See <rdar://problem/6095286>.
387     static const CFStringRef kUTTypePNG = CFSTR("public.png");
388     static const CFStringRef kUTTypeGIF = CFSTR("com.compuserve.gif");
389
390     if (equalIgnoringCase(mimeType, "image/png"))
391         return kUTTypePNG;
392     if (equalIgnoringCase(mimeType, "image/jpeg"))
393         return jpegUTI();
394     if (equalIgnoringCase(mimeType, "image/gif"))
395         return kUTTypeGIF;
396
397     ASSERT_NOT_REACHED();
398     return kUTTypePNG;
399 #endif
400 }
401
402 static bool CGImageEncodeToData(CGImageRef image, CFStringRef uti, const double* quality, CFMutableDataRef data)
403 {
404     if (!image || !uti || !data)
405         return false;
406
407     RetainPtr<CGImageDestinationRef> destination(AdoptCF, CGImageDestinationCreateWithData(data, uti, 1, 0));
408     if (!destination)
409         return false;
410
411     RetainPtr<CFDictionaryRef> imageProperties = 0;
412     if (CFEqual(uti, jpegUTI()) && quality && *quality >= 0.0 && *quality <= 1.0) {
413         // Apply the compression quality to the JPEG image destination.
414         RetainPtr<CFNumberRef> compressionQuality(AdoptCF, CFNumberCreate(kCFAllocatorDefault, kCFNumberDoubleType, quality));
415         const void* key = kCGImageDestinationLossyCompressionQuality;
416         const void* value = compressionQuality.get();
417         imageProperties.adoptCF(CFDictionaryCreate(0, &key, &value, 1, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks));
418     }
419
420     // Setting kCGImageDestinationBackgroundColor to black for JPEG images in imageProperties would save some math
421     // in the calling functions, but it doesn't seem to work.
422
423     CGImageDestinationAddImage(destination.get(), image, imageProperties.get());
424     return CGImageDestinationFinalize(destination.get());
425 }
426
427 static String CGImageToDataURL(CGImageRef image, const String& mimeType, const double* quality)
428 {
429     RetainPtr<CFStringRef> uti = utiFromMIMEType(mimeType);
430     ASSERT(uti);
431
432     RetainPtr<CFMutableDataRef> data(AdoptCF, CFDataCreateMutable(kCFAllocatorDefault, 0));
433     if (!CGImageEncodeToData(image, uti.get(), quality, data.get()))
434         return "data:,";
435
436     Vector<char> base64Data;
437     base64Encode(reinterpret_cast<const char*>(CFDataGetBytePtr(data.get())), CFDataGetLength(data.get()), base64Data);
438
439     return "data:" + mimeType + ";base64," + base64Data;
440 }
441
442 String ImageBuffer::toDataURL(const String& mimeType, const double* quality, CoordinateSystem) const
443 {
444     ASSERT(MIMETypeRegistry::isSupportedImageMIMETypeForEncoding(mimeType));
445
446     RetainPtr<CFStringRef> uti = utiFromMIMEType(mimeType);
447     ASSERT(uti);
448
449     RefPtr<Uint8ClampedArray> premultipliedData;
450     RetainPtr<CGImageRef> image;
451
452     if (CFEqual(uti.get(), jpegUTI())) {
453         // JPEGs don't have an alpha channel, so we have to manually composite on top of black.
454         premultipliedData = getPremultipliedImageData(IntRect(IntPoint(0, 0), logicalSize()));
455         if (!premultipliedData)
456             return "data:,";
457
458         RetainPtr<CGDataProviderRef> dataProvider;
459         dataProvider.adoptCF(CGDataProviderCreateWithData(0, premultipliedData->data(), 4 * logicalSize().width() * logicalSize().height(), 0));
460         if (!dataProvider)
461             return "data:,";
462
463         image.adoptCF(CGImageCreate(logicalSize().width(), logicalSize().height(), 8, 32, 4 * logicalSize().width(),
464                                     deviceRGBColorSpaceRef(), kCGBitmapByteOrderDefault | kCGImageAlphaNoneSkipLast,
465                                     dataProvider.get(), 0, false, kCGRenderingIntentDefault));
466     } else if (m_resolutionScale == 1)
467         image.adoptCF(copyNativeImage(CopyBackingStore));
468     else {
469         image.adoptCF(copyNativeImage(DontCopyBackingStore));
470         RetainPtr<CGContextRef> context(AdoptCF, CGBitmapContextCreate(0, logicalSize().width(), logicalSize().height(), 8, 4 * logicalSize().width(), deviceRGBColorSpaceRef(), kCGImageAlphaPremultipliedLast));
471         CGContextSetBlendMode(context.get(), kCGBlendModeCopy);
472         CGContextDrawImage(context.get(), CGRectMake(0, 0, logicalSize().width(), logicalSize().height()), image.get());
473         image.adoptCF(CGBitmapContextCreateImage(context.get()));
474     }
475
476     return CGImageToDataURL(image.get(), mimeType, quality);
477 }
478
479 String ImageDataToDataURL(const ImageData& source, const String& mimeType, const double* quality)
480 {
481     ASSERT(MIMETypeRegistry::isSupportedImageMIMETypeForEncoding(mimeType));
482
483     RetainPtr<CFStringRef> uti = utiFromMIMEType(mimeType);
484     ASSERT(uti);
485
486     CGImageAlphaInfo dataAlphaInfo = kCGImageAlphaLast;
487     unsigned char* data = source.data()->data();
488     Vector<uint8_t> premultipliedData;
489
490     if (CFEqual(uti.get(), jpegUTI())) {
491         // JPEGs don't have an alpha channel, so we have to manually composite on top of black.
492         size_t size = 4 * source.width() * source.height();
493         if (!premultipliedData.tryReserveCapacity(size))
494             return "data:,";
495
496         unsigned char *buffer = premultipliedData.data();
497         for (size_t i = 0; i < size; i += 4) {
498             unsigned alpha = data[i + 3];
499             if (alpha != 255) {
500                 buffer[i + 0] = data[i + 0] * alpha / 255;
501                 buffer[i + 1] = data[i + 1] * alpha / 255;
502                 buffer[i + 2] = data[i + 2] * alpha / 255;
503             } else {
504                 buffer[i + 0] = data[i + 0];
505                 buffer[i + 1] = data[i + 1];
506                 buffer[i + 2] = data[i + 2];
507             }
508         }
509
510         dataAlphaInfo = kCGImageAlphaNoneSkipLast; // Ignore the alpha channel.
511         data = premultipliedData.data();
512     }
513
514     RetainPtr<CGDataProviderRef> dataProvider;
515     dataProvider.adoptCF(CGDataProviderCreateWithData(0, data, 4 * source.width() * source.height(), 0));
516     if (!dataProvider)
517         return "data:,";
518
519     RetainPtr<CGImageRef> image;
520     image.adoptCF(CGImageCreate(source.width(), source.height(), 8, 32, 4 * source.width(),
521                                 deviceRGBColorSpaceRef(), kCGBitmapByteOrderDefault | dataAlphaInfo,
522                                 dataProvider.get(), 0, false, kCGRenderingIntentDefault));
523
524     return CGImageToDataURL(image.get(), mimeType, quality);
525 }
526
527 } // namespace WebCore