#include "config.h"
#include "ImageBuffer.h"
#include "GraphicsContext.h"
#include <ApplicationServices/ApplicationServices.h>
#include <wtf/Assertions.h>
using namespace std;
namespace WebCore {
auto_ptr<ImageBuffer> ImageBuffer::create(const IntSize& size, bool grayScale)
{
if (size.width() < 0 || size.height() < 0)
return auto_ptr<ImageBuffer>();
unsigned int bytesPerRow = size.width();
if (!grayScale) {
if (bytesPerRow > 0x3FFFFFFF)
return auto_ptr<ImageBuffer>();
bytesPerRow *= 4;
}
void* imageBuffer = fastCalloc(size.height(), bytesPerRow);
if (!imageBuffer)
return auto_ptr<ImageBuffer>();
CGColorSpaceRef colorSpace = grayScale ? CGColorSpaceCreateDeviceGray() : CGColorSpaceCreateDeviceRGB();
CGContextRef cgContext = CGBitmapContextCreate(imageBuffer, size.width(), size.height(), 8, bytesPerRow,
colorSpace, grayScale ? kCGImageAlphaNone : kCGImageAlphaPremultipliedLast);
CGColorSpaceRelease(colorSpace);
if (!cgContext) {
fastFree(imageBuffer);
return auto_ptr<ImageBuffer>();
}
auto_ptr<GraphicsContext> context(new GraphicsContext(cgContext));
CGContextRelease(cgContext);
return auto_ptr<ImageBuffer>(new ImageBuffer(imageBuffer, size, context));
}
ImageBuffer::ImageBuffer(void* imageData, const IntSize& size, auto_ptr<GraphicsContext> context)
: m_data(imageData)
, m_size(size)
, m_context(context.release())
, m_cgImage(0)
{
}
ImageBuffer::~ImageBuffer()
{
fastFree(m_data);
CGImageRelease(m_cgImage);
}
GraphicsContext* ImageBuffer::context() const
{
return m_context.get();
}
CGImageRef ImageBuffer::cgImage() const
{
if (!m_cgImage) {
ASSERT(context());
m_cgImage = CGBitmapContextCreateImage(context()->platformContext());
}
return m_cgImage;
}
}