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