Exemplo n.º 1
0
static void resolveColorSpace(const SkBitmap& bitmap, CGColorSpaceRef colorSpace)
{
    int width = bitmap.width();
    int height = bitmap.height();
    CGImageRef srcImage = SkCreateCGImageRefWithColorspace(bitmap, colorSpace);
    SkAutoLockPixels lock(bitmap);
    void* pixels = bitmap.getPixels();
    RetainPtr<CGContextRef> cgBitmap(AdoptCF, CGBitmapContextCreate(pixels, width, height, 8, width * 4, deviceRGBColorSpaceRef(), kCGBitmapByteOrder32Host | kCGImageAlphaPremultipliedFirst));
    if (!cgBitmap)
        return;
    CGContextSetBlendMode(cgBitmap.get(), kCGBlendModeCopy);
    CGRect bounds = { {0, 0}, {width, height} };
    CGContextDrawImage(cgBitmap.get(), bounds, srcImage);
}
Exemplo n.º 2
0
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);

    size_t bitsPerComponent;
    CGBitmapInfo info;
    getBitmapInfo(bitmap, &bitsPerComponent, &info, NULL); 

    CGColorSpaceRef cs = CGColorSpaceCreateDeviceRGB();
    CGContextRef ctx = CGBitmapContextCreate(bitmap.getPixels(), w, h,
                                             bitsPerComponent, bitmap.rowBytes(),
                                             cs, info);
    CGColorSpaceRelease(cs);

    if (ctx) {
        CGContextDrawPDFPage(ctx, page);
        CGContextRelease(ctx);
    }

    output->swap(bitmap);
    return true;
}
Exemplo n.º 3
0
void CGImageLuminanceSource::init (CGImageRef cgimage, int left, int top, int width, int height) {
    data_ = 0;
    image_ = cgimage;
    left_ = left;
    top_ = top;
    width_ = width;
    height_ = height;
    dataWidth_ = (int)CGImageGetWidth(image_);
    dataHeight_ = (int)CGImageGetHeight(image_);

    if (left_ + width_ > dataWidth_ ||
        top_ + height_ > dataHeight_ ||
        top_ < 0 ||
        left_ < 0) {
        throw IllegalArgumentException("Crop rectangle does not fit within image data.");
    }

    CGColorSpaceRef space = CGImageGetColorSpace(image_);
    CGColorSpaceModel model = CGColorSpaceGetModel(space);

    if (model != kCGColorSpaceModelMonochrome || CGImageGetBitsPerComponent(image_) != 8 || CGImageGetBitsPerPixel(image_) != 8) {
        CGColorSpaceRef gray = CGColorSpaceCreateDeviceGray();
        
        CGContextRef ctx = CGBitmapContextCreate(0, width, height, 8, width, gray, kCGImageAlphaNone);
        
        CGColorSpaceRelease(gray);

        if (top || left) {
            CGContextClipToRect(ctx, CGRectMake(0, 0, width, height));
        }

        CGContextDrawImage(ctx, CGRectMake(-left, -top, width, height), image_);
    
        image_ = CGBitmapContextCreateImage(ctx);

        bytesPerRow_ = width;
        top_ = 0;
        left_ = 0;
        dataWidth_ = width;
        dataHeight_ = height;

        CGContextRelease(ctx);
    } else {
        CGImageRetain(image_);
    }

    CGDataProviderRef provider = CGImageGetDataProvider(image_);
    data_ = CGDataProviderCopyData(provider);
}
Exemplo n.º 4
0
CGContextRef SetupContext()
{
	//UIGraphicsBeginImageContext
	int w = 480, h = 640;
	
	//CGColorSpaceRef csICC = CGColorSpaceCreateWithIndex(15);
	CGColorSpaceRef colourSpace = CGColorSpaceCreateDeviceRGB();
	CGContextRef context = CGBitmapContextCreate(NULL, w, h, 8, CGBitmapGetAlignedBytesPerRow(w*4), colourSpace, kCGImageAlphaPremultipliedFirst);
	CGColorSpaceRelease (colourSpace);
	CGContextClear(context);
	CGContextTranslateCTM(context, 0.0, 640.0);
	CGContextScaleCTM(context, 1.0, -1.0);

   return context;
}
Exemplo n.º 5
0
void ChunkedUpdateDrawingArea::paintIntoUpdateChunk(UpdateChunk* updateChunk)
{
    RetainPtr<CGColorSpaceRef> colorSpace(AdoptCF, CGColorSpaceCreateDeviceRGB());
    RetainPtr<CGContextRef> bitmapContext(AdoptCF, CGBitmapContextCreate(updateChunk->data(), updateChunk->rect().width(), updateChunk->rect().height(), 8, updateChunk->rect().width() * 4, colorSpace.get(), kCGImageAlphaPremultipliedLast));

    // WebCore expects a flipped coordinate system.
    CGContextTranslateCTM(bitmapContext.get(), 0.0, updateChunk->rect().height());
    CGContextScaleCTM(bitmapContext.get(), 1.0, -1.0);

    // Now paint into the backing store.
    GraphicsContext graphicsContext(bitmapContext.get());
    graphicsContext.translate(-updateChunk->rect().x(), -updateChunk->rect().y());
    
    m_webPage->drawRect(graphicsContext, updateChunk->rect());
}
Exemplo n.º 6
0
static CGContextRef makeCG(const SkImageInfo& info, const void* addr,
                           size_t rowBytes) {
    if (kPMColor_SkColorType != info.colorType() || NULL == addr) {
        return NULL;
    }
    CGColorSpaceRef space = CGColorSpaceCreateDeviceRGB();
    CGContextRef cg = CGBitmapContextCreate((void*)addr, info.width(), info.height(),
                                            8, rowBytes, space, BITMAP_INFO_RGB);
    CFRelease(space);

    CGContextSetAllowsFontSubpixelQuantization(cg, false);
    CGContextSetShouldSubpixelQuantizeFonts(cg, false);

    return cg;
}
Exemplo n.º 7
0
bool SkPDFDocumentToBitmap(SkStream* stream, SkBitmap* output) {
    CGDataProviderRef data = SkCreateDataProviderFromStream(stream);
    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;
    if (!bitmap.tryAllocN32Pixels(w, h)) {
        return false;
    }
    bitmap.eraseColor(SK_ColorWHITE);

    size_t bitsPerComponent;
    CGBitmapInfo info;
    getBitmapInfo(bitmap, &bitsPerComponent, &info, NULL);

    CGColorSpaceRef cs = CGColorSpaceCreateDeviceRGB();
    CGContextRef ctx = CGBitmapContextCreate(bitmap.getPixels(), w, h,
                                             bitsPerComponent, bitmap.rowBytes(),
                                             cs, info);
    CGColorSpaceRelease(cs);

    if (ctx) {
        CGContextDrawPDFPage(ctx, page);
        CGContextRelease(ctx);
    }

    output->swap(bitmap);
    return true;
}
Exemplo n.º 8
0
CGImageRef CreatePDFPageImage(CGPDFPageRef page, CGFloat scale, bool transparentBackground)
{
	CGSize pageSize = PDFPageGetSize(page, kCGPDFCropBox);
	
	size_t width = scale * floorf(pageSize.width);
	size_t height = scale * floorf(pageSize.height);
	size_t bytesPerLine = width * 4;
	uint64_t size = (uint64_t)height * (uint64_t)bytesPerLine;
	
	if ((size == 0) || (size > SIZE_MAX))
		return NULL;
	
	void *bitmapData = malloc(size);
	if (!bitmapData)
		return NULL;
	
#if TARGET_OS_IPHONE
	CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
#else
	CGColorSpaceRef colorSpace = CGColorSpaceCreateWithName(&kCGColorSpaceSRGB ? kCGColorSpaceSRGB : kCGColorSpaceGenericRGB);
#endif
	CGContextRef context = CGBitmapContextCreate(bitmapData, width, height, 8, bytesPerLine, colorSpace, kCGImageAlphaPremultipliedFirst);
	
	if (transparentBackground)
	{
		CGContextClearRect(context, CGRectMake(0, 0, width, height));
	}
	else
	{
		CGContextSetRGBFillColor(context, 1, 1, 1, 1); // white
		CGContextFillRect(context, CGRectMake(0, 0, width, height));
	}
	
	// CGPDFPageGetDrawingTransform unfortunately does not upscale, see http://lists.apple.com/archives/quartz-dev/2005/Mar/msg00112.html
	CGAffineTransform drawingTransform = PDFPageGetDrawingTransform(page, kCGPDFCropBox, scale);
	CGContextConcatCTM(context, drawingTransform);
	
	CGContextDrawPDFPage(context, page);
	
	CGImageRef pdfImage = CGBitmapContextCreateImage(context);
	
	CGContextRelease(context);
	CGColorSpaceRelease(colorSpace);
	free(bitmapData);
	
	return pdfImage;
}
PassRefPtr<BitmapContext> createBitmapContextFromWebView(bool onscreen, bool incrementalRepaint, bool sweepHorizontally, bool drawSelectionRect)
{
    RECT frame;
    if (!GetWindowRect(webViewWindow, &frame))
        return nullptr;

    BITMAPINFO bmp = {0};
    bmp.bmiHeader.biSize = sizeof(BITMAPINFOHEADER);
    bmp.bmiHeader.biWidth = frame.right - frame.left;
    bmp.bmiHeader.biHeight = -(frame.bottom - frame.top);
    bmp.bmiHeader.biPlanes = 1;
    bmp.bmiHeader.biBitCount = 32;
    bmp.bmiHeader.biCompression = BI_RGB;

    void* bits = 0;
    HBITMAP bitmap = ::CreateDIBSection(0, &bmp, DIB_RGB_COLORS, &bits, 0, 0);
    if (!bitmap)
        return nullptr;

    auto memoryDC = adoptGDIObject(::CreateCompatibleDC(0));
    ::SelectObject(memoryDC.get(), bitmap);
    SendMessage(webViewWindow, WM_PRINT, reinterpret_cast<WPARAM>(memoryDC.get()), PRF_CLIENT | PRF_CHILDREN | PRF_OWNED);

    BITMAP info = {0};
    GetObject(bitmap, sizeof(info), &info);
    ASSERT(info.bmBitsPixel == 32);

    // We create a context that has an alpha channel below so that the PNGs we generate will also
    // have an alpha channel. But WM_PRINT doesn't necessarily write anything into the alpha
    // channel, so we set the alpha channel to constant full opacity to make sure the resulting image is opaque.
    makeAlphaChannelOpaque(info.bmBits, info.bmWidth, info.bmHeight);

#if USE(CG)
    RetainPtr<CGColorSpaceRef> colorSpace = adoptCF(CGColorSpaceCreateDeviceRGB());
    CGContextRef context = CGBitmapContextCreate(info.bmBits, info.bmWidth, info.bmHeight, 8,
                                                info.bmWidthBytes, colorSpace.get(), kCGBitmapByteOrder32Host | kCGImageAlphaPremultipliedFirst);
#elif USE(CAIRO) 
    cairo_surface_t* image = cairo_image_surface_create_for_data((unsigned char*)info.bmBits, CAIRO_FORMAT_ARGB32, 
                                                      info.bmWidth, info.bmHeight, info.bmWidthBytes); 
    cairo_t* context = cairo_create(image); 
    cairo_surface_destroy(image); 
#endif 

   return BitmapContext::createByAdoptingBitmapAndContext(bitmap, context);
}
Exemplo n.º 10
0
PassRefPtr<Image> ImageBuffer::copyImage(BackingStoreCopy copyBehavior) const
{
    RetainPtr<CGImageRef> image;
    if (m_resolutionScale == 1)
        image = copyNativeImage(copyBehavior);
    else {
        image.adoptCF(copyNativeImage(DontCopyBackingStore));
        RetainPtr<CGContextRef> context(AdoptCF, CGBitmapContextCreate(0, logicalSize().width(), logicalSize().height(), 8, 4 * logicalSize().width(), deviceRGBColorSpaceRef(), kCGImageAlphaPremultipliedLast));
        CGContextSetBlendMode(context.get(), kCGBlendModeCopy);
        CGContextDrawImage(context.get(), CGRectMake(0, 0, logicalSize().width(), logicalSize().height()), image.get());
        image = CGBitmapContextCreateImage(context.get());
    }

    if (!image)
        return 0;

    return BitmapImage::create(image.get());
}
Exemplo n.º 11
0
static void copyImageData_color( CGImageRef imageRef, cv::Mat &image )
{
    size_t width = CGImageGetWidth(imageRef);
    size_t height = CGImageGetHeight(imageRef);
    image = cv::Mat( cv::Size( width, height ), CV_8UC3 );
    CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
    unsigned char *rawData = image.data;
    size_t bytesPerPixel = 4;
    size_t bytesPerRow = bytesPerPixel * width;
    size_t bitsPerComponent = 8;
    CGContextRef context = CGBitmapContextCreate(rawData, width, height,
                                                 bitsPerComponent, bytesPerRow, colorSpace,
                                                 kCGImageAlphaPremultipliedLast | kCGBitmapByteOrderDefault);
    CGColorSpaceRelease(colorSpace);
    
    CGContextDrawImage(context, CGRectMake(0, 0, width, height), imageRef);
    CGContextRelease(context);
}
Exemplo n.º 12
0
draw__Bitmap draw__new_bitmap(int w, int h) {
  init_if_needed();

  int bytes_per_row = w * 4;
  draw__Bitmap bitmap = CGBitmapContextCreate(NULL,   // data
                                              w,
                                              h,
                                              8,      // bits per component
                                              bytes_per_row,
                                              generic_rgb_colorspace,
                                              (CGBitmapInfo)kCGImageAlphaPremultipliedLast);

  // Make (0, 0) correspond to the lower-left corner.
  CGContextTranslateCTM(bitmap, 0, h);
  CGContextScaleCTM(bitmap, 1.0, -1.0);

  return bitmap;
}
Exemplo n.º 13
0
QNativeImage::QNativeImage(int width, int height, QImage::Format format, bool /* isTextBuffer */, QWidget *)
    : image(width, height, format)
{
    cgColorSpace = CGColorSpaceCreateDeviceRGB();
    uint cgflags = kCGImageAlphaNoneSkipFirst;

#ifdef kCGBitmapByteOrder32Host //only needed because CGImage.h added symbols in the minor version
    if(QSysInfo::MacintoshVersion >= QSysInfo::MV_10_4)
        cgflags |= kCGBitmapByteOrder32Host;
#endif

    cg = CGBitmapContextCreate(image.bits(), width, height, 8, image.bytesPerLine(), cgColorSpace, cgflags);
    CGContextTranslateCTM(cg, 0, height);
    CGContextScaleCTM(cg, 1, -1);

    Q_ASSERT(image.paintEngine()->type() == QPaintEngine::Raster);
    static_cast<QRasterPaintEngine *>(image.paintEngine())->setCGContext(cg);
}
Exemplo n.º 14
0
bool MCTileCacheCoreGraphicsCompositor_AllocateTile(void *p_context, int32_t p_size, const void *p_bits, uint32_t p_stride, void*& r_tile)
{
	MCTileCacheCoreGraphicsCompositorContext *self;
	self = (MCTileCacheCoreGraphicsCompositorContext *)p_context;
	
	// If the stride is exactly one tile wide, we don't need a copy.
	void *t_data;
	t_data = nil;
	if (p_stride == p_size * sizeof(uint32_t))
		t_data = (void *)p_bits;
	else if (MCMemoryAllocate(p_size * p_size * sizeof(uint32_t), t_data))
	{
		// Copy across each scanline of the tile into the buffer.
		for(int32_t y = 0; y < p_size; y++)
			memcpy((uint8_t *)t_data + y * p_size * sizeof(uint32_t), (uint8_t *)p_bits + p_stride * y, p_size * sizeof(uint32_t));
	}
	
	CGImageRef t_tile;
	t_tile = nil;
	if (t_data != nil)
	{
		// IM-2013-08-21: [[ RefactorGraphics ]] Refactor CGImage creation code to be pixel-format independent
		CGBitmapInfo t_bm_info;
		t_bm_info = MCGPixelFormatToCGBitmapInfo(kMCGPixelFormatNative, true);
		
		CGContextRef t_cgcontext;
		t_cgcontext = CGBitmapContextCreate((void *)t_data, p_size, p_size, 8, p_size * sizeof(uint32_t), self -> colorspace, t_bm_info);
		if (t_cgcontext != nil)
		{
			t_tile = CGBitmapContextCreateImage(t_cgcontext);
			CGContextRelease(t_cgcontext);
		}
	}
	
	if (t_data != p_bits)
		MCMemoryDeallocate(t_data);
		
	if (t_tile == nil)
		return false;

	r_tile = t_tile;
	
	return true;
}
Exemplo n.º 15
0
GDIObject<HBITMAP> allocImage(HDC dc, IntSize size, CGContextRef *targetRef)
{
    BitmapInfo bmpInfo = BitmapInfo::create(size);

    LPVOID bits;
    auto hbmp = adoptGDIObject(::CreateDIBSection(dc, &bmpInfo, DIB_RGB_COLORS, &bits, 0, 0));

    if (!targetRef)
        return hbmp;

    CGContextRef bitmapContext = CGBitmapContextCreate(bits, bmpInfo.bmiHeader.biWidth, bmpInfo.bmiHeader.biHeight, 8,
                                                       bmpInfo.bmiHeader.biWidth * 4, deviceRGBColorSpaceRef(),
                                                       kCGBitmapByteOrder32Little | kCGImageAlphaNoneSkipFirst);
    if (!bitmapContext)
        return GDIObject<HBITMAP>();

    *targetRef = bitmapContext;
    return hbmp;
}
Exemplo n.º 16
0
CGImageRef Image::createAbstraction(float stylization, uint quantization)
{
	pixel4b *rgbPixels = (pixel4b *) CFDataGetMutableBytePtr(_data);
	
	// Convert from RGB to Lab colorspace to perform operations on lightness channel.
	RGBtoLab(rgbPixels, _pixels);
	
	// Initial bilateral filter.
	bilateral();
	
	// Extract edges.
	pixel3f *edges = createEdges(stylization);
	
	// Additional bilateral filtering.
	bilateral();
	bilateral();
	
	// Quantize lightness channel.
	quantize(quantization);
	 
	// Overlay edges.
	overlayEdges(edges);
	 
	// Convert back to RGB colorspace.
	LabtoRGB(_pixels, rgbPixels);
	
	// Create an image from the modified data.
	CGContextRef context = CGBitmapContextCreate(
		rgbPixels,
		_width,
		_height,
		_bitsPerComponent,
		_bytesPerRow,
		_colorSpaceRef,
		_bitmapInfo
	);
	
	CGImageRef image = CGBitmapContextCreateImage(context);
	
	delete[] edges;
	
	return image;
}
Exemplo n.º 17
0
String ImageBuffer::toDataURL(const String& mimeType, const double* quality, CoordinateSystem) const
{
    ASSERT(MIMETypeRegistry::isSupportedImageMIMETypeForEncoding(mimeType));

    if (context().isAcceleratedContext())
        flushContext();

    RetainPtr<CFStringRef> uti = utiFromMIMEType(mimeType);
    ASSERT(uti);

    RefPtr<Uint8ClampedArray> premultipliedData;
    RetainPtr<CGImageRef> image;

    if (CFEqual(uti.get(), jpegUTI())) {
        // JPEGs don't have an alpha channel, so we have to manually composite on top of black.
        premultipliedData = getPremultipliedImageData(IntRect(IntPoint(0, 0), logicalSize()));
        if (!premultipliedData)
            return "data:,";

        RetainPtr<CGDataProviderRef> dataProvider;
        dataProvider = adoptCF(CGDataProviderCreateWithData(0, premultipliedData->data(), 4 * logicalSize().width() * logicalSize().height(), 0));
        if (!dataProvider)
            return "data:,";

        image = adoptCF(CGImageCreate(logicalSize().width(), logicalSize().height(), 8, 32, 4 * logicalSize().width(),
                                    deviceRGBColorSpaceRef(), kCGBitmapByteOrderDefault | kCGImageAlphaNoneSkipLast,
                                    dataProvider.get(), 0, false, kCGRenderingIntentDefault));
    } else if (m_resolutionScale == 1) {
        image = copyNativeImage(CopyBackingStore);
        image = createCroppedImageIfNecessary(image.get(), internalSize());
    } else {
        image = copyNativeImage(DontCopyBackingStore);
        RetainPtr<CGContextRef> context = adoptCF(CGBitmapContextCreate(0, logicalSize().width(), logicalSize().height(), 8, 4 * logicalSize().width(), deviceRGBColorSpaceRef(), kCGImageAlphaPremultipliedLast));
        CGContextSetBlendMode(context.get(), kCGBlendModeCopy);
        CGContextClipToRect(context.get(), CGRectMake(0, 0, logicalSize().width(), logicalSize().height()));
        FloatSize imageSizeInUserSpace = scaleSizeToUserSpace(logicalSize(), m_data.backingStoreSize, internalSize());
        CGContextDrawImage(context.get(), CGRectMake(0, 0, imageSizeInUserSpace.width(), imageSizeInUserSpace.height()), image.get());
        image = adoptCF(CGBitmapContextCreateImage(context.get()));
    }

    return CGImageToDataURL(image.get(), mimeType, quality);
}
Exemplo n.º 18
0
void BitmapImage::checkForSolidColor()
{
    m_checkedForSolidColor = true;
    m_isSolidColor = false;

    if (frameCount() > 1)
        return;

    if (!haveFrameAtIndex(0)) {
        IntSize size = m_source.frameSizeAtIndex(0, 0);
        if (size.width() != 1 || size.height() != 1)
            return;

        if (!ensureFrameIsCached(0))
            return;
    }

    CGImageRef image = nullptr;
    if (m_frames.size())
        image = m_frames[0].m_frame;

    if (!image)
        return;

    // Currently we only check for solid color in the important special case of a 1x1 image.
    if (CGImageGetWidth(image) == 1 && CGImageGetHeight(image) == 1) {
        unsigned char pixel[4]; // RGBA
        RetainPtr<CGContextRef> bitmapContext = adoptCF(CGBitmapContextCreate(pixel, 1, 1, 8, sizeof(pixel), deviceRGBColorSpaceRef(),
            kCGImageAlphaPremultipliedLast | kCGBitmapByteOrder32Big));
        if (!bitmapContext)
            return;
        GraphicsContext(bitmapContext.get()).setCompositeOperation(CompositeCopy);
        CGRect destinationRect = CGRectMake(0, 0, 1, 1);
        CGContextDrawImage(bitmapContext.get(), destinationRect, image);
        if (!pixel[3])
            m_solidColor = Color(0, 0, 0, 0);
        else
            m_solidColor = Color(pixel[0] * 255 / pixel[3], pixel[1] * 255 / pixel[3], pixel[2] * 255 / pixel[3], pixel[3]);

        m_isSolidColor = true;
    }
}
Exemplo n.º 19
0
/*! \internal

    Returns the CoreGraphics CGContextRef of the paint device. 0 is
    returned if it can't be obtained. It is the caller's responsibility to
    CGContextRelease the context when finished using it.

    \warning This function is only available on Mac OS X.
    \warning This function is duplicated in qmacstyle_mac.mm
*/
CGContextRef qt_mac_cg_context(const QPaintDevice *pdev)
{

    if (pdev->devType() == QInternal::Image) {
         const QImage *i = static_cast<const  QImage*>(pdev);
         QImage *image = const_cast< QImage*>(i);
        CGColorSpaceRef colorspace = CGColorSpaceCreateDeviceRGB();
        uint flags = kCGImageAlphaPremultipliedFirst;
        flags |= kCGBitmapByteOrder32Host;
        CGContextRef ret = 0;

        ret = CGBitmapContextCreate(image->bits(), image->width(), image->height(),
                                    8, image->bytesPerLine(), colorspace, flags);

        CGContextTranslateCTM(ret, 0, image->height());
        CGContextScaleCTM(ret, 1, -1);
        return ret;
    }
    return 0;
}
Exemplo n.º 20
0
// ImageCodecDrawBand
//		The base image decompressor calls your image decompressor component's ImageCodecDrawBand function
// to decompress a band or frame. Your component must implement this function. If the ImageSubCodecDecompressRecord
// structure specifies a progress function or data-loading function, the base image decompressor will never call ImageCodecDrawBand
// at interrupt time. If the ImageSubCodecDecompressRecord structure specifies a progress function, the base image decompressor
// handles codecProgressOpen and codecProgressClose calls, and your image decompressor component must not implement these functions.
// If not, the base image decompressor may call the ImageCodecDrawBand function at interrupt time.
// When the base image decompressor calls your ImageCodecDrawBand function, your component must perform the decompression specified
// by the fields of the ImageSubCodecDecompressRecord structure. The structure includes any changes your component made to it
// when performing the ImageCodecBeginBand function. If your component supports asynchronous scheduled decompression,
// it may receive more than one ImageCodecBeginBand call before receiving an ImageCodecDrawBand call.
pascal ComponentResult TextSubCodecDrawBand(TextSubGlobals glob, ImageSubCodecDecompressRecord *drp)
{
	TextSubDecompressRecord *myDrp = (TextSubDecompressRecord *)drp->userDecompressRecord;
	CGImageAlphaInfo alphaFormat = (myDrp->pixelFormat == k32ARGBPixelFormat) ? kCGImageAlphaPremultipliedFirst : kCGImageAlphaPremultipliedLast;

    CGContextRef c = CGBitmapContextCreate(drp->baseAddr, myDrp->width, myDrp->height,
										   8, drp->rowBytes,  glob->colorSpace,
										   alphaFormat);
	
	CGContextClearRect(c, CGRectMake(0,0, myDrp->width, myDrp->height));
	
	CFMutableStringRef buf;
	
	if (drp->codecData[0] == '\n' && myDrp->dataSize == 1) goto leave; // skip empty packets
	if (myDrp->dataSize > kMaxSubPacketSize) goto leave; // skip very large packets, they probably cause stack overflows
	
	buf = (CFMutableStringRef)CFStringCreateWithBytesNoCopy(NULL, (UInt8*)drp->codecData, myDrp->dataSize, kCFStringEncodingUTF8, false, kCFAllocatorNull);
	if (!buf) goto leave;
	
	if (glob->translateSRT) {
		CFStringRef origBuf = buf;
		buf = CFStringCreateMutableCopy(NULL, 0, buf);
		CFRelease(origBuf);
		if (!buf) goto leave;
		CFStringFindAndReplace(buf, CFSTR("<i>"),  CFSTR("{\\i1}"), CFRangeMake(0,CFStringGetLength(buf)), 0);
		CFStringFindAndReplace(buf, CFSTR("</i>"), CFSTR("{\\i0}"), CFRangeMake(0,CFStringGetLength(buf)), 0);
		CFStringFindAndReplace(buf, CFSTR("<"),    CFSTR("{"),      CFRangeMake(0,CFStringGetLength(buf)), 0);
		CFStringFindAndReplace(buf, CFSTR(">"),    CFSTR("}"),      CFRangeMake(0,CFStringGetLength(buf)), 0);
	}
	
	SubRendererRenderPacket(glob->ssa, c, buf, myDrp->width, myDrp->height);
	
	if (IsTransparentSubtitleHackEnabled())
		ConvertImageToQDTransparent(drp->baseAddr, myDrp->pixelFormat, drp->rowBytes, myDrp->width, myDrp->height);
		
	CFRelease(buf);
	
leave:
	CGContextRelease(c);
	return noErr;
}
static CGContextRef createAlphaOnlyContext(size_t width, size_t height)
{
    /*	This routine allocates data for a pixel array that contains 
		width*height pixels, each pixel is 1 byte. The format is 
		8 bits per pixel, where the data is the alpha value of the pixel.
	*/
    CGContextRef context;
    size_t bytesPerRow;
    unsigned char *rasterData;
   
    // Minimum bytes per row is 1 byte per sample * number of samples.
    bytesPerRow = width;
    // Round to nearest multiple of BEST_BYTE_ALIGNMENT.
    bytesPerRow = COMPUTE_BEST_BYTES_PER_ROW(bytesPerRow);
    
    // Allocate the data for the raster. The total amount of data is bytesPerRow
    // times the number of rows. The function 'calloc' is used so that the
    // memory is initialized to 0.
    rasterData = calloc(1, bytesPerRow * height);
    if(rasterData == NULL){
		fprintf(stderr, "Couldn't allocate the needed amount of memory!\n");
		return NULL;
    } 
    
    // This type of context is only available in Panther and later, otherwise
    // this fails and returns a NULL context. The color space for an alpha
    // only context is NULL and the BitmapInfo value is kCGImageAlphaOnly.
    context = CGBitmapContextCreate(rasterData, width, height, 8, bytesPerRow, 
					NULL, kCGImageAlphaOnly);
    if(context == NULL){
		// If the context couldn't be created then release the raster memory.
		free(rasterData);
		fprintf(stderr, "Couldn't create the context!\n");
		return NULL;
    }

    // Clear the context bits so they are initially transparent.
    CGContextClearRect(context, CGRectMake(0, 0, width, height));
    
    return context;
}
Exemplo n.º 22
0
OSStatus GeneratePreviewForURL(void *thisInterface, QLPreviewRequestRef preview, CFURLRef url, CFStringRef contentTypeUTI, CFDictionaryRef options)
{
	CGDataProviderRef dataProvider = CGDataProviderCreateWithURL(url);
	if (!dataProvider) return -1;
	CFDataRef data = CGDataProviderCopyData(dataProvider);
	CGDataProviderRelease(dataProvider);
	if (!data) return -1;
	
	int width, height, channels;
	unsigned char* rgbadata = SOIL_load_image_from_memory(CFDataGetBytePtr(data), CFDataGetLength(data), &width, &height, &channels, SOIL_LOAD_RGBA);
	CFStringRef format=CFStringCreateWithBytes(NULL, CFDataGetBytePtr(data) + 0x54, 4, kCFStringEncodingASCII, false);
    CFRelease(data);
	if (!rgbadata) return -1;
	
	CGColorSpaceRef rgb = CGColorSpaceCreateDeviceRGB();
	CGContextRef context = CGBitmapContextCreate(rgbadata, width, height, 8, width * 4, rgb, kCGImageAlphaPremultipliedLast);
	SOIL_free_image_data(rgbadata);
	CGColorSpaceRelease(rgb);
	if (!context) return -1;

	CGImageRef image = CGBitmapContextCreateImage(context);
	CGContextRelease(context);
	if (!image) return -1;

	/* Add basic metadata to title */
	CFStringRef name = CFURLCopyLastPathComponent(url);
	CFTypeRef keys[1] = {kQLPreviewPropertyDisplayNameKey};
	CFTypeRef values[1] = {CFStringCreateWithFormat(NULL, NULL, CFSTR("%@ (%dx%d %@)"), name, width, height, format)};
 	CFDictionaryRef properties = CFDictionaryCreate(NULL, (const void**)keys, (const void**)values, 1, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks);
	CFRelease(name);

	context = QLPreviewRequestCreateContext(preview, CGSizeMake(width, height), true, properties);
	CGContextDrawImage(context, CGRectMake(0, 0, width, height), image);
	QLPreviewRequestFlushContext(preview, context);
	
	CGContextRelease(context);
	CFRelease(format);
	CFRelease(properties);
	
	return noErr;
}
Exemplo n.º 23
0
int main (int argc, const char * argv[])
{
    if(argc >= 2) {
        CGPDFDocumentRef doc = CGPDFDocumentCreateWithProvider(CGDataProviderCreateWithFilename(argv[1]));
        size_t pages = CGPDFDocumentGetNumberOfPages(doc);
        
        printf("%lu pages\n", pages);
        
        for(size_t i = 1; i <= pages; i++) {
            char filename[1024];
            
            snprintf(filename, 1024, "%s.%03lu.png", argv[1], i);
            
            printf("writing file: %s\n", filename);
         
            CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
            CGContextRef context = CGBitmapContextCreate(NULL, SIZE, SIZE, 8, 4 * SIZE, colorSpace, kCGImageAlphaPremultipliedLast);
            CGColorSpaceRelease(colorSpace);
            
            CGContextDrawPDFDocument(context, CGRectMake(0, 0, SIZE, SIZE), doc, (int)i);
            
            CGImageRef image = CGBitmapContextCreateImage(context);
            
            CGImageDestinationRef dest = CGImageDestinationCreateWithURL(CFURLCreateWithFileSystemPath(kCFAllocatorDefault, CFStringCreateWithCString(kCFAllocatorDefault, filename, kCFStringEncodingASCII), kCFURLPOSIXPathStyle, false), kUTTypePNG, 1, NULL);
            
            CGImageDestinationAddImage(dest, image, NULL);
            
            CGImageDestinationFinalize(dest);
            
            CGImageRelease(image);
            CGContextRelease(context);
        }
        
        CGPDFDocumentRelease(doc);
    } else {
        printf("pdf2png [filename]\n");
        return 1;
    }
    
    return 0;
}
Exemplo n.º 24
0
void BitmapImage::checkForSolidColor()
{
    m_checkedForSolidColor = true;
    if (frameCount() > 1) {
        m_isSolidColor = false;
        return;
    }

#if !PLATFORM(IOS)
    CGImageRef image = frameAtIndex(0);
#else
    // Note, checkForSolidColor() may be called from frameAtIndex(). On iOS frameAtIndex() gets passed a scaleHint
    // argument which it uses to tell CG to create a scaled down image. Since we don't know the scaleHint here, if
    // we call frameAtIndex() again, we would pass it the default scale of 1 and would end up recreating the image.
    // So we do a quick check and call frameAtIndex(0) only if we haven't yet created an image.
    CGImageRef image = nullptr;
    if (m_frames.size())
        image = m_frames[0].m_frame;

    if (!image)
        image = frameAtIndex(0);
#endif

    // Currently we only check for solid color in the important special case of a 1x1 image.
    if (image && CGImageGetWidth(image) == 1 && CGImageGetHeight(image) == 1) {
        unsigned char pixel[4]; // RGBA
        RetainPtr<CGContextRef> bitmapContext = adoptCF(CGBitmapContextCreate(pixel, 1, 1, 8, sizeof(pixel), deviceRGBColorSpaceRef(),
                                                kCGImageAlphaPremultipliedLast | kCGBitmapByteOrder32Big));
        if (!bitmapContext)
            return;
        GraphicsContext(bitmapContext.get()).setCompositeOperation(CompositeCopy);
        CGRect destinationRect = CGRectMake(0, 0, 1, 1);
        CGContextDrawImage(bitmapContext.get(), destinationRect, image);
        if (!pixel[3])
            m_solidColor = Color(0, 0, 0, 0);
        else
            m_solidColor = Color(pixel[0] * 255 / pixel[3], pixel[1] * 255 / pixel[3], pixel[2] * 255 / pixel[3], pixel[3]);

        m_isSolidColor = true;
    }
}
Exemplo n.º 25
0
RefPtr<Image> ImageBuffer::copyImage(BackingStoreCopy copyBehavior, ScaleBehavior scaleBehavior) const
{
    RetainPtr<CGImageRef> image;
    if (m_resolutionScale == 1 || scaleBehavior == Unscaled) {
        image = copyNativeImage(copyBehavior);
        image = createCroppedImageIfNecessary(image.get(), internalSize());
    } else {
        image = copyNativeImage(DontCopyBackingStore);
        RetainPtr<CGContextRef> context = adoptCF(CGBitmapContextCreate(0, logicalSize().width(), logicalSize().height(), 8, 4 * logicalSize().width(), deviceRGBColorSpaceRef(), kCGImageAlphaPremultipliedLast));
        CGContextSetBlendMode(context.get(), kCGBlendModeCopy);
        CGContextClipToRect(context.get(), FloatRect(FloatPoint::zero(), logicalSize()));
        FloatSize imageSizeInUserSpace = scaleSizeToUserSpace(logicalSize(), m_data.backingStoreSize, internalSize());
        CGContextDrawImage(context.get(), FloatRect(FloatPoint::zero(), imageSizeInUserSpace), image.get());
        image = adoptCF(CGBitmapContextCreateImage(context.get()));
    }

    if (!image)
        return nullptr;

    return BitmapImage::create(image.get());
}
Exemplo n.º 26
0
CGImageRef CGimageResize(CGImageRef image, CGSize maxSize)
{
    // calcualte size
    CGFloat ratio = MAX(CGImageGetWidth(image)/maxSize.width,CGImageGetHeight(image)/maxSize.height);
    size_t width = CGImageGetWidth(image)/ratio;
    size_t height = CGImageGetHeight(image)/ratio;
    // resize
    CGColorSpaceRef colorspace = CGColorSpaceCreateDeviceRGB();
    CGContextRef context = CGBitmapContextCreate(NULL, width, height,
                                                 8, width*4, colorspace, kCGImageAlphaPremultipliedLast);
    CGColorSpaceRelease(colorspace);
    
    if(context == NULL) return nil;
    
    // draw image to context (resizing it)
    CGContextDrawImage(context, CGRectMake(0, 0, width, height), image);
    // extract resulting image from context
    CGImageRef imgRef = CGBitmapContextCreateImage(context);
    CGContextRelease(context);
    
    return imgRef;
}
Exemplo n.º 27
0
PassRefPtr<BitmapImage> BitmapImage::create(HBITMAP hBitmap)
{
    DIBSECTION dibSection;
    if (!GetObject(hBitmap, sizeof(DIBSECTION), &dibSection))
        return 0;

    ASSERT(dibSection.dsBm.bmBitsPixel == 32);
    if (dibSection.dsBm.bmBitsPixel != 32)
        return 0;

    ASSERT(dibSection.dsBm.bmBits);
    if (!dibSection.dsBm.bmBits)
        return 0;

    RetainPtr<CGContextRef> bitmapContext(AdoptCF, CGBitmapContextCreate(dibSection.dsBm.bmBits, dibSection.dsBm.bmWidth, dibSection.dsBm.bmHeight, 8,
        dibSection.dsBm.bmWidthBytes, deviceRGBColorSpaceRef(), kCGBitmapByteOrder32Little | kCGImageAlphaPremultipliedFirst));

    // The BitmapImage takes ownership of this.
    CGImageRef cgImage = CGBitmapContextCreateImage(bitmapContext.get());

    return adoptRef(new BitmapImage(cgImage));
}
Exemplo n.º 28
0
static CGContextRef createContextWithBitmap(CFX_DIBitmap* pBitmap)
{
    if (!pBitmap || pBitmap->IsCmykImage() || pBitmap->GetBPP() < 32) {
        return NULL;
    }
    CGBitmapInfo bitmapInfo = kCGBitmapByteOrder32Little;
    if (pBitmap->HasAlpha()) {
        bitmapInfo |= kCGImageAlphaPremultipliedFirst;
    } else {
        bitmapInfo |= kCGImageAlphaNoneSkipFirst;
    }
    CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
    CGContextRef context = CGBitmapContextCreate(pBitmap->GetBuffer(),
                           pBitmap->GetWidth(),
                           pBitmap->GetHeight(),
                           8,
                           pBitmap->GetPitch(),
                           colorSpace,
                           bitmapInfo);
    CGColorSpaceRelease(colorSpace);
    return context;
}
Exemplo n.º 29
0
cv::Mat &osx_cv::toMat(
        const CGImageRef &image,
        cv::Mat &out,
        osx::disp::RGBType destType
        ) {
    cv::Mat temp;

    size_t w = CGImageGetWidth(image), h = CGImageGetHeight(image);

    if (CGImageGetBitsPerPixel(image) != 32) {
        throw invalid_argument("`image` must be 32 bits per pixel");
    }

    temp.create(int(h), int(w), CV_8UC4);

    CGColorSpaceRef colorSpace = CGImageGetColorSpace(image);

    CGContextRef context = CGBitmapContextCreate(
            temp.data,
            w,
            h,
            CGImageGetBitsPerComponent(image),
            CGImageGetBytesPerRow(image),
            colorSpace,
            CGImageGetAlphaInfo(image)
    );

    CGContextDrawImage(
            context,
            CGRectMake(0, 0, (CGFloat)w, (CGFloat)h),
            image
            );

    _cvtRGBColor(temp, out, CGImageGetAlphaInfo(image), destType);

    CGContextRelease(context);

    return out;
}
Exemplo n.º 30
0
PassRefPtr<BitmapContext> createBitmapContextFromWebView(bool onscreen, bool incrementalRepaint, bool sweepHorizontally, bool drawSelectionRect)
{
    RECT frame;
    if (!GetWindowRect(webViewWindow, &frame))
        return 0;

    BITMAPINFO bmp = {0};
    bmp.bmiHeader.biSize = sizeof(BITMAPINFOHEADER);
    bmp.bmiHeader.biWidth = frame.right - frame.left;
    bmp.bmiHeader.biHeight = -(frame.bottom - frame.top);
    bmp.bmiHeader.biPlanes = 1;
    bmp.bmiHeader.biBitCount = 32;
    bmp.bmiHeader.biCompression = BI_RGB;

    void* bits = 0;
    HBITMAP bitmap = CreateDIBSection(0, &bmp, DIB_RGB_COLORS, &bits, 0, 0);

    HDC memoryDC = CreateCompatibleDC(0);
    SelectObject(memoryDC, bitmap);
    SendMessage(webViewWindow, WM_PRINT, reinterpret_cast<WPARAM>(memoryDC), PRF_CLIENT | PRF_CHILDREN | PRF_OWNED);
    DeleteDC(memoryDC);

    BITMAP info = {0};
    GetObject(bitmap, sizeof(info), &info);
    ASSERT(info.bmBitsPixel == 32);

#if USE(CG)
    RetainPtr<CGColorSpaceRef> colorSpace(AdoptCF, CGColorSpaceCreateDeviceRGB());
    CGContextRef context = CGBitmapContextCreate(info.bmBits, info.bmWidth, info.bmHeight, 8,
                                                info.bmWidthBytes, colorSpace.get(), kCGBitmapByteOrder32Host | kCGImageAlphaPremultipliedFirst);
#elif USE(CAIRO) 
    cairo_surface_t* image = cairo_image_surface_create_for_data((unsigned char*)info.bmBits, CAIRO_FORMAT_ARGB32, 
                                                      info.bmWidth, info.bmHeight, info.bmWidthBytes); 
    cairo_t* context = cairo_create(image); 
    cairo_surface_destroy(image); 
#endif 

   return BitmapContext::createByAdoptingBitmapAndContext(bitmap, context);
}