2
* Copyright (C) 2010 Igalia S.L.
4
* This library is free software; you can redistribute it and/or
5
* modify it under the terms of the GNU Lesser General Public
6
* License as published by the Free Software Foundation; either
7
* version 2 of the License, or (at your option) any later version.
9
* This library is distributed in the hope that it will be useful,
10
* but WITHOUT ANY WARRANTY; without even the implied warranty of
11
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
12
* Lesser General Public License for more details.
14
* You should have received a copy of the GNU Lesser General Public
15
* License along with this library; if not, write to the Free Software
16
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
20
#include "ImageBuffer.h"
22
#include "GdkCairoUtilities.h"
23
#include <wtf/gobject/GOwnPtr.h>
24
#include "GRefPtrGtk.h"
25
#include "MIMETypeRegistry.h"
28
#include <wtf/text/Base64.h>
29
#include <wtf/text/CString.h>
30
#include <wtf/text/WTFString.h>
34
static bool encodeImage(cairo_surface_t* surface, const String& mimeType, const double* quality, GOwnPtr<gchar>& buffer, gsize& bufferSize)
36
// List of supported image encoding types comes from the GdkPixbuf documentation.
37
// http://developer.gnome.org/gdk-pixbuf/stable/gdk-pixbuf-File-saving.html#gdk-pixbuf-save-to-bufferv
39
String type = mimeType.substring(sizeof "image");
40
if (type != "jpeg" && type != "png" && type != "tiff" && type != "ico" && type != "bmp")
43
GRefPtr<GdkPixbuf> pixbuf;
45
// JPEG doesn't support alpha channel. The <canvas> spec states that toDataURL() must encode a Porter-Duff
46
// composite source-over black for image types that do not support alpha.
47
RefPtr<cairo_surface_t> newSurface = adoptRef(cairo_image_surface_create_for_data(cairo_image_surface_get_data(surface),
49
cairo_image_surface_get_width(surface),
50
cairo_image_surface_get_height(surface),
51
cairo_image_surface_get_stride(surface)));
52
pixbuf = adoptGRef(cairoImageSurfaceToGdkPixbuf(newSurface.get()));
54
pixbuf = adoptGRef(cairoImageSurfaceToGdkPixbuf(surface));
59
if (type == "jpeg" && quality && *quality >= 0.0 && *quality <= 1.0) {
60
String qualityString = String::format("%d", static_cast<int>(*quality * 100.0 + 0.5));
61
gdk_pixbuf_save_to_buffer(pixbuf.get(), &buffer.outPtr(), &bufferSize, type.utf8().data(), &error, "quality", qualityString.utf8().data(), NULL);
63
gdk_pixbuf_save_to_buffer(pixbuf.get(), &buffer.outPtr(), &bufferSize, type.utf8().data(), &error, NULL);
68
String ImageBuffer::toDataURL(const String& mimeType, const double* quality, CoordinateSystem) const
70
ASSERT(MIMETypeRegistry::isSupportedImageMIMETypeForEncoding(mimeType));
72
GOwnPtr<gchar> buffer(0);
74
if (!encodeImage(m_data.m_surface, mimeType, quality, buffer, bufferSize))
77
Vector<char> base64Data;
78
base64Encode(buffer.get(), bufferSize, base64Data);
80
return "data:" + mimeType + ";base64," + base64Data;