void QuartzBitmap_Output(QuartzDesc_t dev, QuartzBitmapDevice *qbd) { if(qbd->path && qbd->uti) { /* On 10.4+ we can employ the CGImageDestination API to create a variety of different bitmap formats */ #if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_4 char buf[PATH_MAX+1]; snprintf(buf, PATH_MAX, qbd->path, qbd->page); buf[PATH_MAX] = '\0'; CFStringRef pathString = CFStringCreateWithBytes(kCFAllocatorDefault, (UInt8*) buf, strlen(buf), kCFStringEncodingUTF8, FALSE); CFURLRef path; if(CFStringFind(pathString, CFSTR("://"), 0).location != kCFNotFound) { CFStringRef pathEscaped = CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault, pathString, NULL, NULL, kCFStringEncodingUTF8); path = CFURLCreateWithString(kCFAllocatorDefault, pathEscaped, NULL); CFRelease(pathEscaped); } else { path = CFURLCreateFromFileSystemRepresentation(kCFAllocatorDefault, (const UInt8*) buf, strlen(buf), FALSE); } CFRelease(pathString); CFStringRef scheme = CFURLCopyScheme(path); CFStringRef type = CFStringCreateWithBytes(kCFAllocatorDefault, (UInt8*) qbd->uti, strlen(qbd->uti), kCFStringEncodingUTF8, FALSE); CGImageRef image = CGBitmapContextCreateImage(qbd->bitmap); if(CFStringCompare(scheme,CFSTR("file"), 0) == 0) { /* file output */ CGImageDestinationRef dest = CGImageDestinationCreateWithURL(path, type, 1, NULL); if(dest) { CGImageDestinationAddImage(dest, image, NULL); CGImageDestinationFinalize(dest); CFRelease(dest); } else error(_("QuartzBitmap_Output - unable to open file '%s'"), buf); } else if(CFStringCompare(scheme, CFSTR("clipboard"), 0) == 0) { /* clipboard output */ CFMutableDataRef data = CFDataCreateMutable(kCFAllocatorDefault, 0); CGImageDestinationRef dest = CGImageDestinationCreateWithData(data, type, 1, NULL); CGImageDestinationAddImage(dest, image, NULL); CGImageDestinationFinalize(dest); CFRelease(dest); PasteboardRef pb = NULL; if(PasteboardCreate(kPasteboardClipboard, &pb) == noErr) { PasteboardClear(pb); PasteboardSynchronize(pb); PasteboardPutItemFlavor(pb, (PasteboardItemID) 1, type, data, 0); } CFRelease(data); } else warning(_("not a supported scheme, no image data written")); CFRelease(scheme); CFRelease(type); CFRelease(path); CFRelease(image); #endif } }
static void dumpBitmap(CGContextRef bitmapContext, const char* checksum) { RetainPtr<CGImageRef> image = adoptCF(CGBitmapContextCreateImage(bitmapContext)); RetainPtr<CFMutableDataRef> imageData = adoptCF(CFDataCreateMutable(0, 0)); RetainPtr<CGImageDestinationRef> imageDest = adoptCF(CGImageDestinationCreateWithData(imageData.get(), kUTTypePNG, 1, 0)); CGImageDestinationAddImage(imageDest.get(), image.get(), 0); CGImageDestinationFinalize(imageDest.get()); const unsigned char* data = CFDataGetBytePtr(imageData.get()); const size_t dataLength = CFDataGetLength(imageData.get()); printPNG(data, dataLength, checksum); }
int main(int argc, char** argv) { if (argc <= 1 || !*(argv[1]) || 0 == strcmp(argv[1], "-")) { fprintf(stderr, "usage:\n\t%s INPUT_PDF_FILE_PATH [OUTPUT_PNG_PATH]\n", argv[0]); return 1; } const char* output = argc > 2 ? argv[2] : nullptr; CGDataProviderRef data = CGDataProviderCreateWithFilename(argv[1]); ASSERT(data); CGPDFDocumentRef pdf = CGPDFDocumentCreateWithProvider(data); CGDataProviderRelease(data); ASSERT(pdf); CGPDFPageRef page = CGPDFDocumentGetPage(pdf, PAGE); ASSERT(page); CGRect bounds = CGPDFPageGetBoxRect(page, kCGPDFMediaBox); int w = (int)CGRectGetWidth(bounds); int h = (int)CGRectGetHeight(bounds); CGBitmapInfo info = kCGBitmapByteOrder32Big | kCGImageAlphaPremultipliedLast; CGColorSpaceRef cs = CGColorSpaceCreateDeviceRGB(); ASSERT(cs); std::unique_ptr<uint32_t[]> bitmap(new uint32_t[w * h]); memset(bitmap.get(), 0xFF, 4 * w * h); CGContextRef ctx = CGBitmapContextCreate(bitmap.get(), w, h, 8, w * 4, cs, info); ASSERT(ctx); CGContextDrawPDFPage(ctx, page); CGPDFDocumentRelease(pdf); CGImageRef image = CGBitmapContextCreateImage(ctx); ASSERT(image); CGDataConsumerCallbacks procs; procs.putBytes = [](void* f, const void* buf, size_t s) { return fwrite(buf, 1, s, (FILE*)f); }; procs.releaseConsumer = [](void* info) { fclose((FILE*)info); }; FILE* ofile = (!output || !output[0] || 0 == strcmp(output, "-")) ? stdout : fopen(output, "wb"); ASSERT(ofile); CGDataConsumerRef consumer = CGDataConsumerCreate(ofile, &procs); ASSERT(consumer); CGImageDestinationRef dst = CGImageDestinationCreateWithDataConsumer(consumer, kUTTypePNG, 1, nullptr); CFRelease(consumer); ASSERT(dst); CGImageDestinationAddImage(dst, image, nullptr); ASSERT(CGImageDestinationFinalize(dst)); CFRelease(dst); CGImageRelease(image); CGColorSpaceRelease(cs); CGContextRelease(ctx); return 0; }
void BackingStore::paint(WebCore::GraphicsContext* context, const WebCore::IntRect& clipRect) { // FIXME: Honor the clip rect! OwnPtr<GraphicsContext> sourceContext(createGraphicsContext()); // FIXME: This creates an extra copy. RetainPtr<CGImageRef> image(AdoptCF, CGBitmapContextCreateImage(sourceContext->platformContext())); CGContextRef cgContext = context->platformContext(); CGContextSaveGState(cgContext); CGContextDrawImage(context->platformContext(), CGRectMake(0, 0, CGImageGetWidth(image.get()), CGImageGetHeight(image.get())), image.get()); CGContextRestoreGState(cgContext); }
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); }
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<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()); }
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; }
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; }
String ImageBuffer::toDataURL(const String& mimeType, const double* quality) const { ASSERT(MIMETypeRegistry::isSupportedImageMIMETypeForEncoding(mimeType)); RetainPtr<CGImageRef> image; if (!m_accelerateRendering) image.adoptCF(CGBitmapContextCreateImage(context()->platformContext())); #if USE(IOSURFACE_CANVAS_BACKING_STORE) else image.adoptCF(wkIOSurfaceContextCreateImage(context()->platformContext())); #endif if (!image) return "data:,"; RetainPtr<CFMutableDataRef> data(AdoptCF, CFDataCreateMutable(kCFAllocatorDefault, 0)); if (!data) return "data:,"; RetainPtr<CFStringRef> uti = utiFromMIMEType(mimeType); ASSERT(uti); RetainPtr<CGImageDestinationRef> destination(AdoptCF, CGImageDestinationCreateWithData(data.get(), uti.get(), 1, 0)); if (!destination) return "data:,"; RetainPtr<CFDictionaryRef> imageProperties = 0; if (CFEqual(uti.get(), jpegUTI()) && quality && *quality >= 0.0 && *quality <= 1.0) { // Apply the compression quality to the image destination. RetainPtr<CFNumberRef> compressionQuality(AdoptCF, CFNumberCreate(kCFAllocatorDefault, kCFNumberDoubleType, quality)); const void* key = kCGImageDestinationLossyCompressionQuality; const void* value = compressionQuality.get(); imageProperties.adoptCF(CFDictionaryCreate(0, &key, &value, 1, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks)); } CGImageDestinationAddImage(destination.get(), image.get(), imageProperties.get()); CGImageDestinationFinalize(destination.get()); Vector<char> out; base64Encode(reinterpret_cast<const char*>(CFDataGetBytePtr(data.get())), CFDataGetLength(data.get()), out); return makeString("data:", mimeType, ";base64,", out); }
DragImageRef scaleDragImage(DragImageRef image, FloatSize scale) { // FIXME: due to the way drag images are done on windows we need // to preprocess the alpha channel <rdar://problem/5015946> if (!image) return 0; CGContextRef targetContext; CGContextRef srcContext; CGImageRef srcImage; IntSize srcSize = dragImageSize(image); IntSize dstSize(static_cast<int>(srcSize.width() * scale.width()), static_cast<int>(srcSize.height() * scale.height())); HBITMAP hbmp = 0; HDC dc = GetDC(0); HDC dstDC = CreateCompatibleDC(dc); if (!dstDC) goto exit; hbmp = allocImage(dstDC, dstSize, &targetContext); if (!hbmp) goto exit; srcContext = createCgContextFromBitmap(image); srcImage = CGBitmapContextCreateImage(srcContext); CGRect rect; rect.origin.x = 0; rect.origin.y = 0; rect.size = dstSize; CGContextDrawImage(targetContext, rect, srcImage); CGImageRelease(srcImage); CGContextRelease(srcContext); CGContextRelease(targetContext); ::DeleteObject(image); image = 0; exit: if (!hbmp) hbmp = image; if (dstDC) DeleteDC(dstDC); ReleaseDC(0, dc); return hbmp; }
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); }
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; }
CFX_QuartzDeviceDriver::CFX_QuartzDeviceDriver(CGContextRef context, FX_INT32 deviceClass) { m_saveCount = 0; _context = context; _deviceClass = deviceClass; CGContextRetain(_context); CGRect r = CGContextGetClipBoundingBox(context); _width = FXSYS_round(r.size.width); _height = FXSYS_round(r.size.height); _renderCaps = FXRC_SOFT_CLIP | FXRC_BLEND_MODE | FXRC_ALPHA_PATH | FXRC_ALPHA_IMAGE | FXRC_BIT_MASK | FXRC_ALPHA_MASK; if (_deviceClass != FXDC_DISPLAY) { } else { CGImageRef image = CGBitmapContextCreateImage(_context); if (image) { _renderCaps |= FXRC_GET_BITS; _width = CGImageGetWidth(image); _height = CGImageGetHeight(image); CGImageAlphaInfo alphaInfo = CGImageGetAlphaInfo(image); if (kCGImageAlphaPremultipliedFirst == alphaInfo || kCGImageAlphaPremultipliedLast == alphaInfo || kCGImageAlphaOnly == alphaInfo) { _renderCaps |= FXRC_ALPHA_OUTPUT; } } CGImageRelease(image); } CGAffineTransform ctm = CGContextGetCTM(_context); CGContextSaveGState(_context); m_saveCount++; if (ctm.d >= 0) { CGFloat offset_x, offset_y; offset_x = ctm.tx; offset_y = ctm.ty; CGContextTranslateCTM(_context, -offset_x, -offset_y); CGContextConcatCTM(_context, CGAffineTransformMake(1, 0, 0, -1, offset_x, _height + offset_y)); } _foxitDevice2User = CGAffineTransformIdentity; _user2FoxitDevice = CGAffineTransformInvert(_foxitDevice2User); }
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; }
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()); }
DragImageRef scaleDragImage(DragImageRef imageRef, FloatSize scale) { // FIXME: due to the way drag images are done on windows we need // to preprocess the alpha channel <rdar://problem/5015946> if (!imageRef) return 0; GDIObject<HBITMAP> hbmp; auto image = adoptGDIObject(imageRef); IntSize srcSize = dragImageSize(image.get()); IntSize dstSize(static_cast<int>(srcSize.width() * scale.width()), static_cast<int>(srcSize.height() * scale.height())); HWndDC dc(0); auto dstDC = adoptGDIObject(::CreateCompatibleDC(dc)); if (!dstDC) goto exit; CGContextRef targetContext; hbmp = allocImage(dstDC.get(), dstSize, &targetContext); if (!hbmp) goto exit; CGContextRef srcContext = createCgContextFromBitmap(image.get()); CGImageRef srcImage = CGBitmapContextCreateImage(srcContext); CGRect rect; rect.origin.x = 0; rect.origin.y = 0; rect.size = dstSize; CGContextDrawImage(targetContext, rect, srcImage); CGImageRelease(srcImage); CGContextRelease(srcContext); CGContextRelease(targetContext); exit: if (!hbmp) hbmp.swap(image); return hbmp.leak(); }
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)); }
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; }
int main(int argc, const char * argv[]) { size_t width = 2000; size_t height = 2000; CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB(); CGContextRef context = CGBitmapContextCreate(nullptr, width, height, 8, width * 4, colorSpace, kCGImageAlphaNoneSkipLast); CGColorSpaceRelease(colorSpace); const std::vector<uint8_t> fontVector = generateFont(); std::ofstream outputFile("/Volumes/Data/home/mmaxfield/tmp/output.otf", std::ios::out | std::ios::binary); for (uint8_t b : fontVector) outputFile << b; outputFile.close(); CFDataRef fontData = CFDataCreate(kCFAllocatorDefault, fontVector.data(), fontVector.size()); CTFontDescriptorRef fontDescriptor = CTFontManagerCreateFontDescriptorFromData(fontData); CFRelease(fontData); CFTypeRef featureValues[] = { CFSTR("liga"), CFSTR("clig"), CFSTR("dlig"), CFSTR("hlig"), CFSTR("calt"), CFSTR("subs"), CFSTR("sups"), CFSTR("smcp"), CFSTR("c2sc"), CFSTR("pcap"), CFSTR("c2pc"), CFSTR("unic"), CFSTR("titl"), CFSTR("onum"), CFSTR("pnum"), CFSTR("tnum"), CFSTR("frac"), CFSTR("afrc"), CFSTR("ordn"), CFSTR("zero"), CFSTR("hist"), CFSTR("jp78"), CFSTR("jp83"), CFSTR("jp90"), CFSTR("jp04"), CFSTR("smpl"), CFSTR("trad"), CFSTR("fwid"), CFSTR("pwid"), CFSTR("ruby") }; CFArrayRef features = CFArrayCreate(kCFAllocatorDefault, featureValues, 30, &kCFTypeArrayCallBacks); for (CFIndex i = 0; i < CFArrayGetCount(features); ++i) { drawTextWithFeature(context, fontDescriptor, static_cast<CFStringRef>(CFArrayGetValueAtIndex(features, i)), 1, CGPointMake(25, 1950 - 50 * i)); drawTextWithFeature(context, fontDescriptor, static_cast<CFStringRef>(CFArrayGetValueAtIndex(features, i)), 0, CGPointMake(25, 1925 - 50 * i)); } CFRelease(features); CFRelease(fontDescriptor); CGImageRef image = CGBitmapContextCreateImage(context); CGContextRelease(context); CFURLRef url = CFURLCreateWithFileSystemPath(kCFAllocatorDefault, CFSTR("/Volumes/Data/home/mmaxfield/tmp/output.png"), kCFURLPOSIXPathStyle, FALSE); CGImageDestinationRef imageDestination = CGImageDestinationCreateWithURL(url, kUTTypePNG, 1, nullptr); CFRelease(url); CGImageDestinationAddImage(imageDestination, image, nullptr); CGImageRelease(image); CGImageDestinationFinalize(imageDestination); CFRelease(imageDestination); return 0; }
RetainPtr<CGImageRef> ImageBuffer::copyNativeImage(BackingStoreCopy copyBehavior) const { RetainPtr<CGImageRef> image; if (!context().isAcceleratedContext()) { switch (copyBehavior) { case DontCopyBackingStore: image = adoptCF(CGImageCreate(m_data.backingStoreSize.width(), m_data.backingStoreSize.height(), 8, 32, m_data.bytesPerRow.unsafeGet(), m_data.colorSpace, m_data.bitmapInfo, m_data.dataProvider.get(), 0, true, kCGRenderingIntentDefault)); break; case CopyBackingStore: image = adoptCF(CGBitmapContextCreateImage(context().platformContext())); break; default: ASSERT_NOT_REACHED(); break; } } #if USE(IOSURFACE_CANVAS_BACKING_STORE) else image = m_data.surface->createImage(); #endif return image; }
NativeImagePtr ImageBuffer::copyNativeImage(BackingStoreCopy copyBehavior) const { CGImageRef image = 0; if (!m_context->isAcceleratedContext()) { switch (copyBehavior) { case DontCopyBackingStore: image = CGImageCreate(m_size.width(), m_size.height(), 8, 32, m_data.m_bytesPerRow.unsafeGet(), m_data.m_colorSpace, m_data.m_bitmapInfo, m_data.m_dataProvider.get(), 0, true, kCGRenderingIntentDefault); break; case CopyBackingStore: image = CGBitmapContextCreateImage(context()->platformContext()); break; default: ASSERT_NOT_REACHED(); break; } } #if USE(IOSURFACE_CANVAS_BACKING_STORE) else image = wkIOSurfaceContextCreateImage(context()->platformContext()); #endif return image; }
void ImageBufferData::putData(Uint8ClampedArray*& source, const IntSize& sourceSize, const IntRect& sourceRect, const IntPoint& destPoint, const IntSize& size, bool accelerateRendering, bool unmultiplied, float resolutionScale) { ASSERT(sourceRect.width() > 0); ASSERT(sourceRect.height() > 0); int originx = sourceRect.x(); int destx = (destPoint.x() + sourceRect.x()) * resolutionScale; ASSERT(destx >= 0); ASSERT(destx < size.width()); ASSERT(originx >= 0); ASSERT(originx <= sourceRect.maxX()); int endx = (destPoint.x() + sourceRect.maxX()) * resolutionScale; ASSERT(endx <= size.width()); int width = sourceRect.width(); int destw = endx - destx; int originy = sourceRect.y(); int desty = (destPoint.y() + sourceRect.y()) * resolutionScale; ASSERT(desty >= 0); ASSERT(desty < size.height()); ASSERT(originy >= 0); ASSERT(originy <= sourceRect.maxY()); int endy = (destPoint.y() + sourceRect.maxY()) * resolutionScale; ASSERT(endy <= size.height()); int height = sourceRect.height(); int desth = endy - desty; if (width <= 0 || height <= 0) return; unsigned srcBytesPerRow = 4 * sourceSize.width(); unsigned char* srcRows = source->data() + originy * srcBytesPerRow + originx * 4; unsigned destBytesPerRow; unsigned char* destRows; if (!accelerateRendering) { destBytesPerRow = 4 * size.width(); destRows = reinterpret_cast<unsigned char*>(m_data) + desty * destBytesPerRow + destx * 4; #if USE(ACCELERATE) if (haveVImageRoundingErrorFix() && unmultiplied) { vImage_Buffer src; src.height = height; src.width = width; src.rowBytes = srcBytesPerRow; src.data = srcRows; vImage_Buffer dst; dst.height = desth; dst.width = destw; dst.rowBytes = destBytesPerRow; dst.data = destRows; if (resolutionScale != 1) { vImage_AffineTransform scaleTransform = { resolutionScale, 0, 0, resolutionScale, 0, 0 }; // FIXME: Add subpixel translation. Pixel_8888 backgroundColor; vImageAffineWarp_ARGB8888(&src, &dst, 0, &scaleTransform, backgroundColor, kvImageEdgeExtend); // The premultiplying will be done in-place. src = dst; } vImagePremultiplyData_RGBA8888(&src, &dst, kvImageNoFlags); return; } #endif if (resolutionScale != 1) { RetainPtr<CGContextRef> sourceContext(AdoptCF, CGBitmapContextCreate(srcRows, width, height, 8, srcBytesPerRow, m_colorSpace, kCGImageAlphaPremultipliedLast)); RetainPtr<CGImageRef> sourceImage(AdoptCF, CGBitmapContextCreateImage(sourceContext.get())); RetainPtr<CGContextRef> destinationContext(AdoptCF, CGBitmapContextCreate(destRows, destw, desth, 8, destBytesPerRow, m_colorSpace, kCGImageAlphaPremultipliedLast)); CGContextSetBlendMode(destinationContext.get(), kCGBlendModeCopy); CGContextDrawImage(destinationContext.get(), CGRectMake(0, 0, width / resolutionScale, height / resolutionScale), sourceImage.get()); // FIXME: Add subpixel translation. if (!unmultiplied) return; srcRows = destRows; srcBytesPerRow = destBytesPerRow; width = destw; height = desth; } for (int y = 0; y < height; ++y) { for (int x = 0; x < width; x++) { int basex = x * 4; unsigned char alpha = srcRows[basex + 3]; if (unmultiplied && alpha != 255) { destRows[basex] = (srcRows[basex] * alpha + 254) / 255; destRows[basex + 1] = (srcRows[basex + 1] * alpha + 254) / 255; destRows[basex + 2] = (srcRows[basex + 2] * alpha + 254) / 255; destRows[basex + 3] = alpha; } else reinterpret_cast<uint32_t*>(destRows + basex)[0] = reinterpret_cast<uint32_t*>(srcRows + basex)[0]; } destRows += destBytesPerRow; srcRows += srcBytesPerRow; } } else { #if USE(IOSURFACE_CANVAS_BACKING_STORE) IOSurfaceRef surface = m_surface.get(); IOSurfaceLock(surface, 0, 0); destBytesPerRow = IOSurfaceGetBytesPerRow(surface); destRows = (unsigned char*)(IOSurfaceGetBaseAddress(surface)) + desty * destBytesPerRow + destx * 4; #if USE(ACCELERATE) vImage_Buffer src; src.height = height; src.width = width; src.rowBytes = srcBytesPerRow; src.data = srcRows; vImage_Buffer dest; dest.height = desth; dest.width = destw; dest.rowBytes = destBytesPerRow; dest.data = destRows; if (resolutionScale != 1) { vImage_AffineTransform scaleTransform = { resolutionScale, 0, 0, resolutionScale, 0, 0 }; // FIXME: Add subpixel translation. Pixel_8888 backgroundColor; vImageAffineWarp_ARGB8888(&src, &dest, 0, &scaleTransform, backgroundColor, kvImageEdgeExtend); // The unpremultiplying and channel-swapping will be done in-place. if (unmultiplied) { srcRows = destRows; width = destw; height = desth; srcBytesPerRow = destBytesPerRow; } else src = dest; } if (unmultiplied) { ScanlineData scanlineData; scanlineData.scanlineWidth = width; scanlineData.srcData = srcRows; scanlineData.srcRowBytes = srcBytesPerRow; scanlineData.destData = destRows; scanlineData.destRowBytes = destBytesPerRow; dispatch_apply_f(height, dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), &scanlineData, premultitplyScanline); } else { // Swap pixel channels from RGBA to BGRA. const uint8_t map[4] = { 2, 1, 0, 3 }; vImagePermuteChannels_ARGB8888(&src, &dest, map, kvImageNoFlags); } #else if (resolutionScale != 1) { RetainPtr<CGContextRef> sourceContext(AdoptCF, CGBitmapContextCreate(srcRows, width, height, 8, srcBytesPerRow, m_colorSpace, kCGImageAlphaPremultipliedLast)); RetainPtr<CGImageRef> sourceImage(AdoptCF, CGBitmapContextCreateImage(sourceContext.get())); RetainPtr<CGContextRef> destinationContext(AdoptCF, CGBitmapContextCreate(destRows, destw, desth, 8, destBytesPerRow, m_colorSpace, kCGImageAlphaPremultipliedLast)); CGContextSetBlendMode(destinationContext.get(), kCGBlendModeCopy); CGContextDrawImage(destinationContext.get(), CGRectMake(0, 0, width / resolutionScale, height / resolutionScale), sourceImage.get()); // FIXME: Add subpixel translation. srcRows = destRows; srcBytesPerRow = destBytesPerRow; width = destw; height = desth; } for (int y = 0; y < height; ++y) { for (int x = 0; x < width; x++) { int basex = x * 4; unsigned char b = srcRows[basex]; unsigned char alpha = srcRows[basex + 3]; if (unmultiplied && alpha != 255) { destRows[basex] = (srcRows[basex + 2] * alpha + 254) / 255; destRows[basex + 1] = (srcRows[basex + 1] * alpha + 254) / 255; destRows[basex + 2] = (b * alpha + 254) / 255; destRows[basex + 3] = alpha; } else { destRows[basex] = srcRows[basex + 2]; destRows[basex + 1] = srcRows[basex + 1]; destRows[basex + 2] = b; destRows[basex + 3] = alpha; } } destRows += destBytesPerRow; srcRows += srcBytesPerRow; } #endif // USE(ACCELERATE) IOSurfaceUnlock(surface, 0, 0); #else ASSERT_NOT_REACHED(); #endif // USE(IOSURFACE_CANVAS_BACKING_STORE) } }
PassRefPtr<Uint8ClampedArray> ImageBufferData::getData(const IntRect& rect, const IntSize& size, bool accelerateRendering, bool unmultiplied, float resolutionScale) const { float area = 4.0f * rect.width() * rect.height(); if (area > static_cast<float>(std::numeric_limits<int>::max())) return 0; RefPtr<Uint8ClampedArray> result = Uint8ClampedArray::createUninitialized(rect.width() * rect.height() * 4); unsigned char* data = result->data(); int endx = ceilf(rect.maxX() * resolutionScale); int endy = ceilf(rect.maxY() * resolutionScale); if (rect.x() < 0 || rect.y() < 0 || endx > size.width() || endy > size.height()) result->zeroFill(); int originx = rect.x(); int destx = 0; int destw = rect.width(); if (originx < 0) { destw += originx; destx = -originx; originx = 0; } destw = min<int>(destw, ceilf(size.width() / resolutionScale) - originx); originx *= resolutionScale; if (endx > size.width()) endx = size.width(); int width = endx - originx; int originy = rect.y(); int desty = 0; int desth = rect.height(); if (originy < 0) { desth += originy; desty = -originy; originy = 0; } desth = min<int>(desth, ceilf(size.height() / resolutionScale) - originy); originy *= resolutionScale; if (endy > size.height()) endy = size.height(); int height = endy - originy; if (width <= 0 || height <= 0) return result.release(); unsigned destBytesPerRow = 4 * rect.width(); unsigned char* destRows = data + desty * destBytesPerRow + destx * 4; unsigned srcBytesPerRow; unsigned char* srcRows; if (!accelerateRendering) { srcBytesPerRow = 4 * size.width(); srcRows = reinterpret_cast<unsigned char*>(m_data) + originy * srcBytesPerRow + originx * 4; #if USE(ACCELERATE) if (unmultiplied && haveVImageRoundingErrorFix()) { vImage_Buffer src; src.height = height; src.width = width; src.rowBytes = srcBytesPerRow; src.data = srcRows; vImage_Buffer dst; dst.height = desth; dst.width = destw; dst.rowBytes = destBytesPerRow; dst.data = destRows; if (resolutionScale != 1) { vImage_AffineTransform scaleTransform = { 1 / resolutionScale, 0, 0, 1 / resolutionScale, 0, 0 }; // FIXME: Add subpixel translation. Pixel_8888 backgroundColor; vImageAffineWarp_ARGB8888(&src, &dst, 0, &scaleTransform, backgroundColor, kvImageEdgeExtend); // The unpremultiplying will be done in-place. src = dst; } vImageUnpremultiplyData_RGBA8888(&src, &dst, kvImageNoFlags); return result.release(); } #endif if (resolutionScale != 1) { RetainPtr<CGContextRef> sourceContext(AdoptCF, CGBitmapContextCreate(srcRows, width, height, 8, srcBytesPerRow, m_colorSpace, kCGImageAlphaPremultipliedLast)); RetainPtr<CGImageRef> sourceImage(AdoptCF, CGBitmapContextCreateImage(sourceContext.get())); RetainPtr<CGContextRef> destinationContext(AdoptCF, CGBitmapContextCreate(destRows, destw, desth, 8, destBytesPerRow, m_colorSpace, kCGImageAlphaPremultipliedLast)); CGContextSetBlendMode(destinationContext.get(), kCGBlendModeCopy); CGContextDrawImage(destinationContext.get(), CGRectMake(0, 0, width / resolutionScale, height / resolutionScale), sourceImage.get()); // FIXME: Add subpixel translation. if (!unmultiplied) return result.release(); srcRows = destRows; srcBytesPerRow = destBytesPerRow; width = destw; height = desth; } if (unmultiplied) { for (int y = 0; y < height; ++y) { for (int x = 0; x < width; x++) { int basex = x * 4; unsigned char alpha = srcRows[basex + 3]; if (alpha) { destRows[basex] = (srcRows[basex] * 255) / alpha; destRows[basex + 1] = (srcRows[basex + 1] * 255) / alpha; destRows[basex + 2] = (srcRows[basex + 2] * 255) / alpha; destRows[basex + 3] = alpha; } else reinterpret_cast<uint32_t*>(destRows + basex)[0] = reinterpret_cast<uint32_t*>(srcRows + basex)[0]; } srcRows += srcBytesPerRow; destRows += destBytesPerRow; } } else { for (int y = 0; y < height; ++y) { for (int x = 0; x < width * 4; x += 4) reinterpret_cast<uint32_t*>(destRows + x)[0] = reinterpret_cast<uint32_t*>(srcRows + x)[0]; srcRows += srcBytesPerRow; destRows += destBytesPerRow; } } } else { #if USE(IOSURFACE_CANVAS_BACKING_STORE) IOSurfaceRef surface = m_surface.get(); IOSurfaceLock(surface, kIOSurfaceLockReadOnly, 0); srcBytesPerRow = IOSurfaceGetBytesPerRow(surface); srcRows = (unsigned char*)(IOSurfaceGetBaseAddress(surface)) + originy * srcBytesPerRow + originx * 4; #if USE(ACCELERATE) vImage_Buffer src; src.height = height; src.width = width; src.rowBytes = srcBytesPerRow; src.data = srcRows; vImage_Buffer dest; dest.height = desth; dest.width = destw; dest.rowBytes = destBytesPerRow; dest.data = destRows; if (resolutionScale != 1) { vImage_AffineTransform scaleTransform = { 1 / resolutionScale, 0, 0, 1 / resolutionScale, 0, 0 }; // FIXME: Add subpixel translation. Pixel_8888 backgroundColor; vImageAffineWarp_ARGB8888(&src, &dest, 0, &scaleTransform, backgroundColor, kvImageEdgeExtend); // The unpremultiplying and channel-swapping will be done in-place. if (unmultiplied) { srcRows = destRows; width = destw; height = desth; srcBytesPerRow = destBytesPerRow; } else src = dest; } if (unmultiplied) { ScanlineData scanlineData; scanlineData.scanlineWidth = width; scanlineData.srcData = srcRows; scanlineData.srcRowBytes = srcBytesPerRow; scanlineData.destData = destRows; scanlineData.destRowBytes = destBytesPerRow; dispatch_apply_f(height, dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), &scanlineData, unpremultitplyScanline); } else { // Swap pixel channels from BGRA to RGBA. const uint8_t map[4] = { 2, 1, 0, 3 }; vImagePermuteChannels_ARGB8888(&src, &dest, map, kvImageNoFlags); } #else if (resolutionScale != 1) { RetainPtr<CGContextRef> sourceContext(AdoptCF, CGBitmapContextCreate(srcRows, width, height, 8, srcBytesPerRow, m_colorSpace, kCGImageAlphaPremultipliedLast)); RetainPtr<CGImageRef> sourceImage(AdoptCF, CGBitmapContextCreateImage(sourceContext.get())); RetainPtr<CGContextRef> destinationContext(AdoptCF, CGBitmapContextCreate(destRows, destw, desth, 8, destBytesPerRow, m_colorSpace, kCGImageAlphaPremultipliedLast)); CGContextSetBlendMode(destinationContext.get(), kCGBlendModeCopy); CGContextDrawImage(destinationContext.get(), CGRectMake(0, 0, width / resolutionScale, height / resolutionScale), sourceImage.get()); // FIXME: Add subpixel translation. srcRows = destRows; srcBytesPerRow = destBytesPerRow; width = destw; height = desth; } if (unmultiplied) { for (int y = 0; y < height; ++y) { for (int x = 0; x < width; x++) { int basex = x * 4; unsigned char b = srcRows[basex]; unsigned char alpha = srcRows[basex + 3]; if (alpha) { destRows[basex] = (srcRows[basex + 2] * 255) / alpha; destRows[basex + 1] = (srcRows[basex + 1] * 255) / alpha; destRows[basex + 2] = (b * 255) / alpha; destRows[basex + 3] = alpha; } else { destRows[basex] = srcRows[basex + 2]; destRows[basex + 1] = srcRows[basex + 1]; destRows[basex + 2] = b; destRows[basex + 3] = srcRows[basex + 3]; } } srcRows += srcBytesPerRow; destRows += destBytesPerRow; } } else { for (int y = 0; y < height; ++y) { for (int x = 0; x < width; x++) { int basex = x * 4; unsigned char b = srcRows[basex]; destRows[basex] = srcRows[basex + 2]; destRows[basex + 1] = srcRows[basex + 1]; destRows[basex + 2] = b; destRows[basex + 3] = srcRows[basex + 3]; } srcRows += srcBytesPerRow; destRows += destBytesPerRow; } } #endif // USE(ACCELERATE) IOSurfaceUnlock(surface, kIOSurfaceLockReadOnly, 0); #else ASSERT_NOT_REACHED(); #endif // USE(IOSURFACE_CANVAS_BACKING_STORE) } return result.release(); }
void QRasterWindowSurface::flush(QWidget *widget, const QRegion &rgn, const QPoint &offset) { Q_D(QRasterWindowSurface); // Not ready for painting yet, bail out. This can happen in // QWidget::create_sys() if (!d->image || rgn.rectCount() == 0) return; #ifdef Q_WS_WIN QRect br = rgn.boundingRect(); if (!qt_widget_private(window())->isOpaque && window()->testAttribute(Qt::WA_TranslucentBackground) && (qt_widget_private(window())->data.window_flags & Qt::FramelessWindowHint)) { QRect r = window()->frameGeometry(); QPoint frameOffset = qt_widget_private(window())->frameStrut().topLeft(); QRect dirtyRect = br.translated(offset + frameOffset); SIZE size = {r.width(), r.height()}; POINT ptDst = {r.x(), r.y()}; POINT ptSrc = {0, 0}; BLENDFUNCTION blend = {AC_SRC_OVER, 0, (BYTE)(255.0 * window()->windowOpacity()), Q_AC_SRC_ALPHA}; RECT dirty = {dirtyRect.x(), dirtyRect.y(), dirtyRect.x() + dirtyRect.width(), dirtyRect.y() + dirtyRect.height()}; Q_UPDATELAYEREDWINDOWINFO info = {sizeof(info), NULL, &ptDst, &size, d->image->hdc, &ptSrc, 0, &blend, Q_ULW_ALPHA, &dirty}; ptrUpdateLayeredWindowIndirect(window()->internalWinId(), &info); } else { QPoint wOffset = qt_qwidget_data(widget)->wrect.topLeft(); HDC widget_dc = widget->getDC(); QRect wbr = br.translated(-wOffset); BitBlt(widget_dc, wbr.x(), wbr.y(), wbr.width(), wbr.height(), d->image->hdc, br.x() + offset.x(), br.y() + offset.y(), SRCCOPY); widget->releaseDC(widget_dc); } #ifndef QT_NO_DEBUG static bool flush = !qgetenv("QT_FLUSH_WINDOWSURFACE").isEmpty(); if (flush) { SelectObject(qt_win_display_dc(), GetStockObject(BLACK_BRUSH)); Rectangle(qt_win_display_dc(), 0, 0, d->image->width() + 2, d->image->height() + 2); BitBlt(qt_win_display_dc(), 1, 1, d->image->width(), d->image->height(), d->image->hdc, 0, 0, SRCCOPY); } #endif #endif #ifdef Q_WS_X11 extern void *qt_getClipRects(const QRegion &r, int &num); // in qpaintengine_x11.cpp extern QWidgetData* qt_widget_data(QWidget *); QPoint wOffset = qt_qwidget_data(widget)->wrect.topLeft(); if (widget->window() != window()) { XFreeGC(X11->display, d_ptr->gc); d_ptr->gc = XCreateGC(X11->display, widget->handle(), 0, 0); } QRegion wrgn(rgn); if (!wOffset.isNull()) wrgn.translate(-wOffset); if (wrgn.rectCount() != 1) { int num; XRectangle *rects = (XRectangle *)qt_getClipRects(wrgn, num); XSetClipRectangles(X11->display, d_ptr->gc, 0, 0, rects, num, YXBanded); } QPoint widgetOffset = offset + wOffset; QRect clipRect = widget->rect().translated(widgetOffset).intersected(d_ptr->image->image.rect()); QRect br = rgn.boundingRect().translated(offset).intersected(clipRect); QPoint wpos = br.topLeft() - widgetOffset; #ifndef QT_NO_MITSHM if (d_ptr->image->xshmpm) { XCopyArea(X11->display, d_ptr->image->xshmpm, widget->handle(), d_ptr->gc, br.x(), br.y(), br.width(), br.height(), wpos.x(), wpos.y()); d_ptr->needsSync = true; } else if (d_ptr->image->xshmimg) { XShmPutImage(X11->display, widget->handle(), d_ptr->gc, d_ptr->image->xshmimg, br.x(), br.y(), wpos.x(), wpos.y(), br.width(), br.height(), False); d_ptr->needsSync = true; } else #endif { int depth = widget->x11Info().depth(); const QImage &src = d->image->image; if (src.format() != QImage::Format_RGB32 || depth < 24 || X11->bppForDepth.value(depth) != 32) { Q_ASSERT(src.depth() >= 16); const QImage sub_src(src.scanLine(br.y()) + br.x() * (uint(src.depth()) / 8), br.width(), br.height(), src.bytesPerLine(), src.format()); QX11PixmapData *data = new QX11PixmapData(QPixmapData::PixmapType); data->xinfo = widget->x11Info(); data->fromImage(sub_src, Qt::NoOpaqueDetection); QPixmap pm = QPixmap(data); XCopyArea(X11->display, pm.handle(), widget->handle(), d_ptr->gc, 0 , 0 , br.width(), br.height(), wpos.x(), wpos.y()); } else { // qpaintengine_x11.cpp extern void qt_x11_drawImage(const QRect &rect, const QPoint &pos, const QImage &image, Drawable hd, GC gc, Display *dpy, Visual *visual, int depth); qt_x11_drawImage(br, wpos, src, widget->handle(), d_ptr->gc, X11->display, (Visual *)widget->x11Info().visual(), depth); } } if (wrgn.rectCount() != 1) XSetClipMask(X11->display, d_ptr->gc, XNone); #endif // FALCON #ifdef Q_WS_MAC Q_UNUSED(offset); // This is mainly done for native components like native "open file" dialog. if (widget->testAttribute(Qt::WA_DontShowOnScreen)) { return; } #ifdef QT_MAC_USE_COCOA this->needsFlush = true; this->regionToFlush += rgn; // The actual flushing will be processed in [view drawRect:rect] qt_mac_setNeedsDisplay(widget); #else // Get a context for the widget. CGContextRef context; CGrafPtr port = GetWindowPort(qt_mac_window_for(widget)); QDBeginCGContext(port, &context); CGContextRetain(context); CGContextSaveGState(context); // Flip context. CGContextTranslateCTM(context, 0, widget->height()); CGContextScaleCTM(context, 1, -1); // Clip to region. const QVector<QRect> &rects = rgn.rects(); for (int i = 0; i < rects.size(); ++i) { const QRect &rect = rects.at(i); CGContextAddRect(context, CGRectMake(rect.x(), rect.y(), rect.width(), rect.height())); } CGContextClip(context); QRect r = rgn.boundingRect().intersected(d->image->image.rect()); const CGRect area = CGRectMake(r.x(), r.y(), r.width(), r.height()); CGImageRef image = CGBitmapContextCreateImage(d->image->cg); CGImageRef subImage = CGImageCreateWithImageInRect(image, area); qt_mac_drawCGImage(context, &area, subImage); CGImageRelease(subImage); CGImageRelease(image); QDEndCGContext(port, &context); // Restore context. CGContextRestoreGState(context); CGContextRelease(context); #endif // QT_MAC_USE_COCOA #endif // Q_WS_MAC }
static void _GraphicsScreen_cellArrayOrImage (GraphicsScreen me, double **z_float, double_rgbt **z_rgbt, unsigned char **z_byte, long ix1, long ix2, long x1DC, long x2DC, long iy1, long iy2, long y1DC, long y2DC, double minimum, double maximum, long clipx1, long clipx2, long clipy1, long clipy2, int interpolate) { /*long t=clock();*/ long nx = ix2 - ix1 + 1; /* The number of cells along the horizontal axis. */ long ny = iy2 - iy1 + 1; /* The number of cells along the vertical axis. */ double dx = (double) (x2DC - x1DC) / (double) nx; /* Horizontal pixels per cell. Positive. */ double dy = (double) (y2DC - y1DC) / (double) ny; /* Vertical pixels per cell. Negative. */ double scale = 255.0 / (maximum - minimum), offset = 255.0 + minimum * scale; if (x2DC <= x1DC || y1DC <= y2DC) return; trace ("scale %f", scale); /* Clip by the intersection of the world window and the outline of the cells. */ //Melder_casual ("clipy1 %ld clipy2 %ld", clipy1, clipy2); if (clipx1 < x1DC) clipx1 = x1DC; if (clipx2 > x2DC) clipx2 = x2DC; if (clipy1 > y1DC) clipy1 = y1DC; if (clipy2 < y2DC) clipy2 = y2DC; /* * The first decision is whether we are going to use the standard rectangle drawing * (cellArray only), or whether we are going to write into a bitmap. * The standard drawing is best for small numbers of cells, * provided that some cells are larger than a pixel. */ if (! interpolate && nx * ny < 3000 && (dx > 1.0 || dy < -1.0)) { try { /*unsigned int cellWidth = (unsigned int) dx + 1;*/ unsigned int cellHeight = (unsigned int) (- (int) dy) + 1; long ix, iy; #if cairo cairo_pattern_t *grey [256]; for (int igrey = 0; igrey < sizeof (grey) / sizeof (*grey); igrey ++) { double v = igrey / ((double) (sizeof (grey) / sizeof (*grey)) - 1.0); grey [igrey] = cairo_pattern_create_rgb (v, v, v); } #elif win static HBRUSH greyBrush [256]; RECT rect; if (! greyBrush [0]) for (int igrey = 0; igrey <= 255; igrey ++) greyBrush [igrey] = CreateSolidBrush (RGB (igrey, igrey, igrey)); // once #elif mac GraphicsQuartz_initDraw (me); CGContextSetAlpha (my d_macGraphicsContext, 1.0); CGContextSetBlendMode (my d_macGraphicsContext, kCGBlendModeNormal); #endif autoNUMvector <long> lefts (ix1, ix2 + 1); for (ix = ix1; ix <= ix2 + 1; ix ++) lefts [ix] = x1DC + (long) ((ix - ix1) * dx); for (iy = iy1; iy <= iy2; iy ++) { long bottom = y1DC + (long) ((iy - iy1) * dy), top = bottom - cellHeight; if (top > clipy1 || bottom < clipy2) continue; if (top < clipy2) top = clipy2; if (bottom > clipy1) bottom = clipy1; #if win rect. bottom = bottom; rect. top = top; #endif for (ix = ix1; ix <= ix2; ix ++) { long left = lefts [ix], right = lefts [ix + 1]; if (right < clipx1 || left > clipx2) continue; if (left < clipx1) left = clipx1; if (right > clipx2) right = clipx2; if (z_rgbt) { #if cairo // NYI #elif win // NYI #elif mac double red = z_rgbt [iy] [ix]. red; double green = z_rgbt [iy] [ix]. green; double blue = z_rgbt [iy] [ix]. blue; double transparency = z_rgbt [iy] [ix]. transparency; red = ( red <= 0.0 ? 0.0 : red >= 1.0 ? 1.0 : red ); green = ( green <= 0.0 ? 0.0 : green >= 1.0 ? 1.0 : green ); blue = ( blue <= 0.0 ? 0.0 : blue >= 1.0 ? 1.0 : blue ); CGContextSetRGBFillColor (my d_macGraphicsContext, red, green, blue, 1.0 - transparency); CGContextFillRect (my d_macGraphicsContext, CGRectMake (left, top, right - left, bottom - top)); #endif } else { #if cairo long value = offset - scale * ( z_float ? z_float [iy] [ix] : z_byte [iy] [ix] ); cairo_set_source (my d_cairoGraphicsContext, grey [value <= 0 ? 0 : value >= sizeof (grey) / sizeof (*grey) ? sizeof (grey) / sizeof (*grey) : value]); cairo_rectangle (my d_cairoGraphicsContext, left, top, right - left, bottom - top); cairo_fill (my d_cairoGraphicsContext); #elif win long value = offset - scale * ( z_float ? z_float [iy] [ix] : z_byte [iy] [ix] ); rect. left = left; rect. right = right; FillRect (my d_gdiGraphicsContext, & rect, greyBrush [value <= 0 ? 0 : value >= 255 ? 255 : value]); #elif mac double value = offset - scale * ( z_float ? z_float [iy] [ix] : z_byte [iy] [ix] ); double igrey = ( value <= 0 ? 0 : value >= 255 ? 255 : value ) / 255.0; CGContextSetRGBFillColor (my d_macGraphicsContext, igrey, igrey, igrey, 1.0); CGContextFillRect (my d_macGraphicsContext, CGRectMake (left, top, right - left, bottom - top)); #endif } } } #if cairo for (int igrey = 0; igrey < sizeof (grey) / sizeof (*grey); igrey ++) cairo_pattern_destroy (grey [igrey]); #elif mac CGContextSetRGBFillColor (my d_macGraphicsContext, 0.0, 0.0, 0.0, 1.0); GraphicsQuartz_exitDraw (me); #endif } catch (MelderError) { } } else { long xDC, yDC; long undersampling = 1; /* * Prepare for off-screen bitmap drawing. */ #if cairo long arrayWidth = clipx2 - clipx1; long arrayHeight = clipy1 - clipy2; trace ("arrayWidth %f, arrayHeight %f", (double) arrayWidth, (double) arrayHeight); cairo_surface_t *sfc = cairo_image_surface_create (CAIRO_FORMAT_RGB24, arrayWidth, arrayHeight); unsigned char *bits = cairo_image_surface_get_data (sfc); int scanLineLength = cairo_image_surface_get_stride (sfc); unsigned char grey [256]; trace ("image surface address %p, bits address %p, scanLineLength %d, numberOfGreys %d", sfc, bits, scanLineLength, sizeof(grey)/sizeof(*grey)); for (int igrey = 0; igrey < sizeof (grey) / sizeof (*grey); igrey++) grey [igrey] = 255 - (unsigned char) (igrey * 255.0 / (sizeof (grey) / sizeof (*grey) - 1)); #elif win long bitmapWidth = clipx2 - clipx1, bitmapHeight = clipy1 - clipy2; int igrey; /* * Create a device-independent bitmap, 32 bits deep. */ struct { BITMAPINFOHEADER header; } bitmapInfo; long scanLineLength = bitmapWidth * 4; // for 24 bits: (bitmapWidth * 3 + 3) & ~3L; HBITMAP bitmap; unsigned char *bits; // a pointer to memory allocated by VirtualAlloc or by CreateDIBSection () bitmapInfo. header.biSize = sizeof (BITMAPINFOHEADER); bitmapInfo. header.biWidth = bitmapWidth; // scanLineLength; bitmapInfo. header.biHeight = bitmapHeight; bitmapInfo. header.biPlanes = 1; bitmapInfo. header.biBitCount = 32; bitmapInfo. header.biCompression = 0; bitmapInfo. header.biSizeImage = 0; bitmapInfo. header.biXPelsPerMeter = 0; bitmapInfo. header.biYPelsPerMeter = 0; bitmapInfo. header.biClrUsed = 0; bitmapInfo. header.biClrImportant = 0; bitmap = CreateDIBSection (my d_gdiGraphicsContext /* ignored */, (CONST BITMAPINFO *) & bitmapInfo, DIB_RGB_COLORS, (VOID **) & bits, NULL, 0); #elif mac long bytesPerRow = (clipx2 - clipx1) * 4; Melder_assert (bytesPerRow > 0); long numberOfRows = clipy1 - clipy2; Melder_assert (numberOfRows > 0); unsigned char *imageData = Melder_malloc_f (unsigned char, bytesPerRow * numberOfRows); #endif /* * Draw into the bitmap. */ #if cairo #define ROW_START_ADDRESS (bits + (clipy1 - 1 - yDC) * scanLineLength) #define PUT_PIXEL \ if (1) { \ unsigned char kar = value <= 0 ? 0 : value >= 255 ? 255 : (int) value; \ *pixelAddress ++ = kar; \ *pixelAddress ++ = kar; \ *pixelAddress ++ = kar; \ *pixelAddress ++ = 0; \ } #elif win #define ROW_START_ADDRESS (bits + (clipy1 - 1 - yDC) * scanLineLength) #define PUT_PIXEL \ if (1) { \ unsigned char kar = value <= 0 ? 0 : value >= 255 ? 255 : (int) value; \ *pixelAddress ++ = kar; \ *pixelAddress ++ = kar; \ *pixelAddress ++ = kar; \ *pixelAddress ++ = 0; \ } #elif mac #define ROW_START_ADDRESS (imageData + (clipy1 - 1 - yDC) * bytesPerRow) #define PUT_PIXEL \ if (my colourScale == kGraphics_colourScale_GREY) { \ unsigned char kar = value <= 0 ? 0 : value >= 255 ? 255 : (int) value; \ *pixelAddress ++ = kar; \ *pixelAddress ++ = kar; \ *pixelAddress ++ = kar; \ *pixelAddress ++ = 0; \ } else if (my colourScale == kGraphics_colourScale_BLUE_TO_RED) { \ if (value < 0.0) { \ *pixelAddress ++ = 0; \ *pixelAddress ++ = 0; \ *pixelAddress ++ = 63; \ *pixelAddress ++ = 0; \ } else if (value < 64.0) { \ *pixelAddress ++ = 0; \ *pixelAddress ++ = 0; \ *pixelAddress ++ = (int) (value * 3 + 63.999); \ *pixelAddress ++ = 0; \ } else if (value < 128.0) { \ *pixelAddress ++ = (int) (value * 4 - 256.0); \ *pixelAddress ++ = (int) (value * 4 - 256.0); \ *pixelAddress ++ = 255; \ *pixelAddress ++ = 0; \ } else if (value < 192.0) { \ *pixelAddress ++ = 255; \ *pixelAddress ++ = (int) ((256.0 - value) * 4 - 256.0); \ *pixelAddress ++ = (int) ((256.0 - value) * 4 - 256.0); \ *pixelAddress ++ = 0; \ } else if (value < 256.0) { \ *pixelAddress ++ = (int) ((256.0 - value) * 3 + 63.999); \ *pixelAddress ++ = 0; \ *pixelAddress ++ = 0; \ *pixelAddress ++ = 0; \ } else { \ *pixelAddress ++ = 63; \ *pixelAddress ++ = 0; \ *pixelAddress ++ = 0; \ *pixelAddress ++ = 0; \ } \ } #else #define ROW_START_ADDRESS NULL #define PUT_PIXEL #endif if (interpolate) { try { autoNUMvector <long> ileft (clipx1, clipx2); autoNUMvector <long> iright (clipx1, clipx2); autoNUMvector <double> rightWeight (clipx1, clipx2); autoNUMvector <double> leftWeight (clipx1, clipx2); for (xDC = clipx1; xDC < clipx2; xDC += undersampling) { double ix_real = ix1 - 0.5 + ((double) nx * (xDC - x1DC)) / (x2DC - x1DC); ileft [xDC] = floor (ix_real), iright [xDC] = ileft [xDC] + 1; rightWeight [xDC] = ix_real - ileft [xDC], leftWeight [xDC] = 1.0 - rightWeight [xDC]; if (ileft [xDC] < ix1) ileft [xDC] = ix1; if (iright [xDC] > ix2) iright [xDC] = ix2; } for (yDC = clipy2; yDC < clipy1; yDC += undersampling) { double iy_real = iy2 + 0.5 - ((double) ny * (yDC - y2DC)) / (y1DC - y2DC); long itop = ceil (iy_real), ibottom = itop - 1; double bottomWeight = itop - iy_real, topWeight = 1.0 - bottomWeight; unsigned char *pixelAddress = ROW_START_ADDRESS; if (itop > iy2) itop = iy2; if (ibottom < iy1) ibottom = iy1; if (z_float) { double *ztop = z_float [itop], *zbottom = z_float [ibottom]; for (xDC = clipx1; xDC < clipx2; xDC += undersampling) { double interpol = rightWeight [xDC] * (topWeight * ztop [iright [xDC]] + bottomWeight * zbottom [iright [xDC]]) + leftWeight [xDC] * (topWeight * ztop [ileft [xDC]] + bottomWeight * zbottom [ileft [xDC]]); double value = offset - scale * interpol; PUT_PIXEL } } else if (z_rgbt) { double_rgbt *ztop = z_rgbt [itop], *zbottom = z_rgbt [ibottom]; for (xDC = clipx1; xDC < clipx2; xDC += undersampling) { double red = rightWeight [xDC] * (topWeight * ztop [iright [xDC]]. red + bottomWeight * zbottom [iright [xDC]]. red) + leftWeight [xDC] * (topWeight * ztop [ileft [xDC]]. red + bottomWeight * zbottom [ileft [xDC]]. red); double green = rightWeight [xDC] * (topWeight * ztop [iright [xDC]]. green + bottomWeight * zbottom [iright [xDC]]. green) + leftWeight [xDC] * (topWeight * ztop [ileft [xDC]]. green + bottomWeight * zbottom [ileft [xDC]]. green); double blue = rightWeight [xDC] * (topWeight * ztop [iright [xDC]]. blue + bottomWeight * zbottom [iright [xDC]]. blue) + leftWeight [xDC] * (topWeight * ztop [ileft [xDC]]. blue + bottomWeight * zbottom [ileft [xDC]]. blue); double transparency = rightWeight [xDC] * (topWeight * ztop [iright [xDC]]. transparency + bottomWeight * zbottom [iright [xDC]]. transparency) + leftWeight [xDC] * (topWeight * ztop [ileft [xDC]]. transparency + bottomWeight * zbottom [ileft [xDC]]. transparency); if (red < 0.0) red = 0.0; else if (red > 1.0) red = 1.0; if (green < 0.0) green = 0.0; else if (green > 1.0) green = 1.0; if (blue < 0.0) blue = 0.0; else if (blue > 1.0) blue = 1.0; if (transparency < 0.0) transparency = 0.0; else if (transparency > 1.0) transparency = 1.0; #if win *pixelAddress ++ = blue * 255.0; *pixelAddress ++ = green * 255.0; *pixelAddress ++ = red * 255.0; *pixelAddress ++ = 0; #elif mac *pixelAddress ++ = red * 255.0; *pixelAddress ++ = green * 255.0; *pixelAddress ++ = blue * 255.0; *pixelAddress ++ = transparency * 255.0; #elif cairo *pixelAddress ++ = blue * 255.0; *pixelAddress ++ = green * 255.0; *pixelAddress ++ = red * 255.0; *pixelAddress ++ = transparency * 255.0; #endif } } else { unsigned char *ztop = z_byte [itop], *zbottom = z_byte [ibottom]; for (xDC = clipx1; xDC < clipx2; xDC += undersampling) { double interpol = rightWeight [xDC] * (topWeight * ztop [iright [xDC]] + bottomWeight * zbottom [iright [xDC]]) + leftWeight [xDC] * (topWeight * ztop [ileft [xDC]] + bottomWeight * zbottom [ileft [xDC]]); double value = offset - scale * interpol; PUT_PIXEL } } } } catch (MelderError) { Melder_clearError (); } } else { try { autoNUMvector <long> ix (clipx1, clipx2); for (xDC = clipx1; xDC < clipx2; xDC += undersampling) ix [xDC] = floor (ix1 + (nx * (xDC - x1DC)) / (x2DC - x1DC)); for (yDC = clipy2; yDC < clipy1; yDC += undersampling) { long iy = ceil (iy2 - (ny * (yDC - y2DC)) / (y1DC - y2DC)); unsigned char *pixelAddress = ROW_START_ADDRESS; Melder_assert (iy >= iy1 && iy <= iy2); if (z_float) { double *ziy = z_float [iy]; for (xDC = clipx1; xDC < clipx2; xDC += undersampling) { double value = offset - scale * ziy [ix [xDC]]; PUT_PIXEL } } else { unsigned char *ziy = z_byte [iy]; for (xDC = clipx1; xDC < clipx2; xDC += undersampling) { double value = offset - scale * ziy [ix [xDC]]; PUT_PIXEL } } } } catch (MelderError) { Melder_clearError (); } } /* * Copy the bitmap to the screen. */ #if cairo cairo_matrix_t clip_trans; cairo_matrix_init_identity (& clip_trans); cairo_matrix_scale (& clip_trans, 1, -1); // we painted in the reverse y-direction cairo_matrix_translate (& clip_trans, - clipx1, - clipy1); cairo_pattern_t *bitmap_pattern = cairo_pattern_create_for_surface (sfc); trace ("bitmap pattern %p", bitmap_pattern); if (cairo_status_t status = cairo_pattern_status (bitmap_pattern)) { Melder_casual ("bitmap pattern status: %s", cairo_status_to_string (status)); } else { cairo_pattern_set_matrix (bitmap_pattern, & clip_trans); cairo_save (my d_cairoGraphicsContext); cairo_set_source (my d_cairoGraphicsContext, bitmap_pattern); cairo_paint (my d_cairoGraphicsContext); cairo_restore (my d_cairoGraphicsContext); } cairo_pattern_destroy (bitmap_pattern); #elif win SetDIBitsToDevice (my d_gdiGraphicsContext, clipx1, clipy2, bitmapWidth, bitmapHeight, 0, 0, 0, bitmapHeight, bits, (CONST BITMAPINFO *) & bitmapInfo, DIB_RGB_COLORS); //StretchDIBits (my d_gdiGraphicsContext, clipx1, clipy2, bitmapWidth, bitmapHeight, 0, 0, 0, bitmapHeight, // bits, (CONST BITMAPINFO *) & bitmapInfo, DIB_RGB_COLORS, SRCCOPY); #elif mac CGImageRef image; static CGColorSpaceRef colourSpace = NULL; if (colourSpace == NULL) { colourSpace = CGColorSpaceCreateWithName (kCGColorSpaceGenericRGB); // used to be kCGColorSpaceUserRGB Melder_assert (colourSpace != NULL); } if (1) { CGDataProviderRef dataProvider = CGDataProviderCreateWithData (NULL, imageData, bytesPerRow * numberOfRows, _mac_releaseDataCallback // we need this because we cannot release the image data immediately after drawing, // because in PDF files the imageData has to stay available through EndPage ); Melder_assert (dataProvider != NULL); image = CGImageCreate (clipx2 - clipx1, numberOfRows, 8, 32, bytesPerRow, colourSpace, kCGImageAlphaNone, dataProvider, NULL, false, kCGRenderingIntentDefault); CGDataProviderRelease (dataProvider); } else if (0) { Melder_assert (CGBitmapContextCreate != NULL); CGContextRef bitmaptest = CGBitmapContextCreate (imageData, 100, 100, 8, 800, colourSpace, 0); Melder_assert (bitmaptest != NULL); CGContextRef bitmap = CGBitmapContextCreate (NULL/*imageData*/, clipx2 - clipx1, numberOfRows, 8, bytesPerRow, colourSpace, kCGImageAlphaLast); Melder_assert (bitmap != NULL); image = CGBitmapContextCreateImage (bitmap); // release bitmap? } Melder_assert (image != NULL); GraphicsQuartz_initDraw (me); CGContextDrawImage (my d_macGraphicsContext, CGRectMake (clipx1, clipy2, clipx2 - clipx1, clipy1 - clipy2), image); GraphicsQuartz_exitDraw (me); //CGColorSpaceRelease (colourSpace); CGImageRelease (image); #endif /* * Clean up. */ #if cairo cairo_surface_destroy (sfc); #elif win DeleteBitmap (bitmap); #endif }
/* Create a CGImageRef from osg::Image. * Code adapted from * http://developer.apple.com/samplecode/OpenGLScreenSnapshot/listing2.html */ CGImageRef CreateCGImageFromOSGData(const osg::Image& osg_image) { size_t image_width = osg_image.s(); size_t image_height = osg_image.t(); /* From Apple's header for CGBitmapContextCreate() * Each row of the bitmap consists of `bytesPerRow' bytes, which must be at * least `(width * bitsPerComponent * number of components + 7)/8' bytes. */ size_t target_bytes_per_row; CGColorSpaceRef color_space; CGBitmapInfo bitmap_info; /* From what I can figure out so far... * We need to create a CGContext connected to the data we want to save * and then call CGBitmapContextCreateImage() on that context to get * a CGImageRef. * However, OS X only allows 4-component image formats (e.g. RGBA) and not * just RGB for the RGB-based CGContext. So for a 24-bit image coming in, * we need to expand the data to 32-bit. * The easiest and fastest way to do that is through the vImage framework * which is part of the Accelerate framework. * Also, the osg::Image data coming in is inverted from what we want, so * we need to invert the image too. Since the osg::Image is const, * we don't want to touch the data, so again we turn to the vImage framework * and invert the data. */ vImage_Buffer vimage_buffer_in = { (void*)osg_image.data(), // need to override const, but we don't modify the data so it's safe image_height, image_width, osg_image.getRowSizeInBytes() }; void* out_image_data; vImage_Buffer vimage_buffer_out = { NULL, // will fill-in in switch image_height, image_width, 0 // will fill-in in switch }; vImage_Error vimage_error_flag; // FIXME: Do I want to use format, type, or internalFormat? switch(osg_image.getPixelFormat()) { case GL_LUMINANCE: { bitmap_info = kCGImageAlphaNone; target_bytes_per_row = (image_width * 8 + 7)/8; //color_space = CGColorSpaceCreateWithName(kCGColorSpaceGenericGray); color_space = CGColorSpaceCreateDeviceGray(); if(NULL == color_space) { return NULL; } // out_image_data = calloc(target_bytes_per_row, image_height); out_image_data = malloc(target_bytes_per_row * image_height); if(NULL == out_image_data) { OSG_WARN << "In CreateCGImageFromOSGData, malloc failed" << std::endl; CGColorSpaceRelease(color_space); return NULL; } vimage_buffer_out.data = out_image_data; vimage_buffer_out.rowBytes = target_bytes_per_row; // Now invert the image vimage_error_flag = vImageVerticalReflect_Planar8( &vimage_buffer_in, // since the osg_image is const... &vimage_buffer_out, // don't reuse the buffer kvImageNoFlags ); if(vimage_error_flag != kvImageNoError) { OSG_WARN << "In CreateCGImageFromOSGData for GL_LUMINANCE, vImageVerticalReflect_Planar8 failed with vImage Error Code: " << vimage_error_flag << std::endl; free(out_image_data); CGColorSpaceRelease(color_space); return NULL; } break; } case GL_ALPHA: { bitmap_info = kCGImageAlphaOnly; target_bytes_per_row = (image_width * 8 + 7)/8; // According to: // http://developer.apple.com/qa/qa2001/qa1037.html // colorSpace=NULL is for alpha only color_space = NULL; // out_image_data = calloc(target_bytes_per_row, image_height); out_image_data = malloc(target_bytes_per_row * image_height); if(NULL == out_image_data) { OSG_WARN << "In CreateCGImageFromOSGData, malloc failed" << std::endl; return NULL; } vimage_buffer_out.data = out_image_data; vimage_buffer_out.rowBytes = target_bytes_per_row; // Now invert the image vimage_error_flag = vImageVerticalReflect_Planar8( &vimage_buffer_in, // since the osg_image is const... &vimage_buffer_out, // don't reuse the buffer kvImageNoFlags ); if(vimage_error_flag != kvImageNoError) { OSG_WARN << "In CreateCGImageFromOSGData for GL_ALPHA, vImageVerticalReflect_Planar8 failed with vImage Error Code: " << vimage_error_flag << std::endl; free(out_image_data); return NULL; } break; } /* case GL_LUMINANCE_ALPHA: { // I don't know if we can support this. // The qa1037 doesn't show both gray+alpha. break; } */ case GL_RGB: { bitmap_info = kCGImageAlphaNoneSkipFirst; target_bytes_per_row = (image_width * 8 * 4 + 7)/8; //color_space = CGColorSpaceCreateWithName(kCGColorSpaceGenericRGB); color_space = CGColorSpaceCreateDeviceRGB(); if(NULL == color_space) { OSG_WARN << "In CreateCGImageFromOSGData, CGColorSpaceCreateWithName failed" << std::endl; return NULL; } // out_image_data = calloc(target_bytes_per_row, image_height); out_image_data = malloc(target_bytes_per_row * image_height); if(NULL == out_image_data) { OSG_WARN << "In CreateCGImageFromOSGData, malloc failed" << std::endl; CGColorSpaceRelease(color_space); return NULL; } // Use vImage to get an RGB buffer into ARGB. vimage_buffer_out.data = out_image_data; vimage_buffer_out.rowBytes = target_bytes_per_row; vimage_error_flag = vImageConvert_RGB888toARGB8888( &vimage_buffer_in, NULL, // we don't have a buffer containing alpha values 255, // The alpha value we want given to all pixels since we don't have a buffer &vimage_buffer_out, 0, // premultiply? kvImageNoFlags // Only responds to kvImageDoNotTile, but I think we want tiling/threading ); if(vimage_error_flag != kvImageNoError) { OSG_WARN << "In CreateCGImageFromOSGData, vImageConvert_RGB888toARGB8888 failed with vImage Error Code: " << vimage_error_flag << std::endl; free(out_image_data); CGColorSpaceRelease(color_space); return NULL; } // Now invert the image vimage_error_flag = vImageVerticalReflect_ARGB8888( &vimage_buffer_out, &vimage_buffer_out, // reuse the same buffer kvImageNoFlags ); if(vimage_error_flag != kvImageNoError) { OSG_WARN << "In CreateCGImageFromOSGData, vImageAffineWarp_ARGB8888 failed with vImage Error Code: " << vimage_error_flag << std::endl; free(out_image_data); CGColorSpaceRelease(color_space); return NULL; } break; } case GL_RGBA: { bitmap_info = kCGImageAlphaPremultipliedLast; target_bytes_per_row = osg_image.getRowSizeInBytes(); //color_space = CGColorSpaceCreateWithName(kCGColorSpaceGenericRGB); color_space = CGColorSpaceCreateDeviceRGB(); if(NULL == color_space) { OSG_WARN << "In CreateCGImageFromOSGData, CGColorSpaceCreateWithName failed" << std::endl; return NULL; } // out_image_data = calloc(target_bytes_per_row, image_height); out_image_data = malloc(target_bytes_per_row * image_height); if(NULL == out_image_data) { OSG_WARN << "In CreateCGImageFromOSGData, malloc failed" << std::endl; CGColorSpaceRelease(color_space); return NULL; } vimage_buffer_out.data = out_image_data; vimage_buffer_out.rowBytes = target_bytes_per_row; // Invert the image vimage_error_flag = vImageVerticalReflect_ARGB8888( &vimage_buffer_in, // since the osg_image is const... &vimage_buffer_out, // don't reuse the buffer kvImageNoFlags ); if(vimage_error_flag != kvImageNoError) { OSG_WARN << "In CreateCGImageFromOSGData, vImageAffineWarp_ARGB8888 failed with vImage Error Code: " << vimage_error_flag << std::endl; free(out_image_data); CGColorSpaceRelease(color_space); return NULL; } break; } case GL_BGRA: { if(GL_UNSIGNED_INT_8_8_8_8_REV == osg_image.getDataType()) { #if __BIG_ENDIAN__ bitmap_info = kCGImageAlphaPremultipliedFirst | kCGBitmapByteOrder32Big; /* XRGB Big Endian */ #else bitmap_info = kCGImageAlphaPremultipliedFirst | kCGBitmapByteOrder32Little; /* XRGB Little Endian */ #endif } else { // FIXME: Don't know how to handle this case bitmap_info = kCGImageAlphaPremultipliedLast; } target_bytes_per_row = osg_image.getRowSizeInBytes(); //color_space = CGColorSpaceCreateWithName(kCGColorSpaceGenericRGB); color_space = CGColorSpaceCreateDeviceRGB(); if(NULL == color_space) { OSG_WARN << "In CreateCGImageFromOSGData, CGColorSpaceCreateWithName failed" << std::endl; return NULL; } // out_image_data = calloc(target_bytes_per_row, image_height); out_image_data = malloc(target_bytes_per_row * image_height); if(NULL == out_image_data) { OSG_WARN << "In CreateCGImageFromOSGData, malloc failed" << std::endl; CGColorSpaceRelease(color_space); return NULL; } vimage_buffer_out.data = out_image_data; vimage_buffer_out.rowBytes = target_bytes_per_row; // Invert the image vimage_error_flag = vImageVerticalReflect_ARGB8888( &vimage_buffer_in, // since the osg_image is const... &vimage_buffer_out, // don't reuse the buffer kvImageNoFlags ); if(vimage_error_flag != kvImageNoError) { OSG_WARN << "In CreateCGImageFromOSGData, vImageAffineWarp_ARGB8888 failed with vImage Error Code: " << vimage_error_flag << std::endl; free(out_image_data); CGColorSpaceRelease(color_space); return NULL; } break; } // FIXME: Handle other cases. // Use vImagePermuteChannels_ARGB8888 to swizzle bytes default: { OSG_WARN << "In CreateCGImageFromOSGData: Sorry support for this format is not implemented." << std::endl; return NULL; break; } } CGContextRef bitmap_context = CGBitmapContextCreate( vimage_buffer_out.data, vimage_buffer_out.width, vimage_buffer_out.height, 8, vimage_buffer_out.rowBytes, color_space, bitmap_info ); /* Done with color space */ CGColorSpaceRelease(color_space); if(NULL == bitmap_context) { free(out_image_data); return NULL; } /* Make an image out of our bitmap; does a cheap vm_copy of the bitmap */ CGImageRef image_ref = CGBitmapContextCreateImage(bitmap_context); /* Done with data */ free(out_image_data); /* Done with bitmap_context */ CGContextRelease(bitmap_context); return image_ref; }
bool ImageIOEncoder::write( const Mat& img, const vector<int>& params ) { int width = img.cols, height = img.rows; int _channels = img.channels(); const uchar* data = img.data; int step = img.step; // Determine the appropriate UTI based on the filename extension CFStringRef imageUTI = FilenameToUTI( m_filename.c_str() ); // Determine the Bytes Per Pixel int bpp = (_channels == 1) ? 1 : 4; // Write the data into a bitmap context CGContextRef context; CGColorSpaceRef colorSpace; uchar* bitmapData = NULL; if( bpp == 1 ) colorSpace = CGColorSpaceCreateWithName( kCGColorSpaceGenericGray ); else if( bpp == 4 ) colorSpace = CGColorSpaceCreateWithName( kCGColorSpaceGenericRGBLinear ); if( !colorSpace ) return false; bitmapData = (uchar*)malloc( bpp * height * width ); if( !bitmapData ) { CGColorSpaceRelease( colorSpace ); return false; } context = CGBitmapContextCreate( bitmapData, width, height, 8, bpp * width, colorSpace, (bpp == 1) ? kCGImageAlphaNone : kCGImageAlphaNoneSkipLast ); CGColorSpaceRelease( colorSpace ); if( !context ) { free( bitmapData ); return false; } // Copy pixel information from data into bitmapData if (bpp == 4) { int bitmapIndex = 0; const uchar * base = data; for (int y = 0; y < height; y++) { const uchar * line = base + y * step; for (int x = 0; x < width; x++) { // Blue channel bitmapData[bitmapIndex + 2] = line[0]; // Green channel bitmapData[bitmapIndex + 1] = line[1]; // Red channel bitmapData[bitmapIndex + 0] = line[2]; line += 3; bitmapIndex += bpp; } } } else if (bpp == 1) { for (int y = 0; y < height; y++) memcpy (bitmapData + y * width, data + y * step, width); } // Turn the bitmap context into an imageRef CGImageRef imageRef = CGBitmapContextCreateImage( context ); CGContextRelease( context ); if( !imageRef ) { free( bitmapData ); return false; } // Write the imageRef to a file based on the UTI CFURLRef imageURLRef = CFURLCreateFromFileSystemRepresentation( NULL, (const UInt8*)m_filename.c_str(), m_filename.size(), false ); if( !imageURLRef ) { CGImageRelease( imageRef ); free( bitmapData ); return false; } CGImageDestinationRef destRef = CGImageDestinationCreateWithURL( imageURLRef, imageUTI, 1, NULL); CFRelease( imageURLRef ); if( !destRef ) { CGImageRelease( imageRef ); free( bitmapData ); fprintf(stderr, "!destRef\n"); return false; } CGImageDestinationAddImage(destRef, imageRef, NULL); if( !CGImageDestinationFinalize(destRef) ) { fprintf(stderr, "Finalize failed\n"); return false; } CFRelease( destRef ); CGImageRelease( imageRef ); free( bitmapData ); return true; }
void x_async_refresh(CGContextRef myContext,CGRect myBoundingBox) { #ifdef ENABLEQD CEmulatorMac* pEmu = (CEmulatorMac*)CEmulator::theEmulator; if (!pEmu) return ; #endif #ifndef DRIVER_IOS x_vbl_count++; #endif addFrameRate(0); CHANGE_BORDER(1,0xFF); // OG if (macUsingCoreGraphics) { if(r_sim65816.is_emulator_offscreen_available() && g_kimage_offscreen.dev_handle) { /* void addConsoleWindow(Kimage* _dst); addConsoleWindow(&g_kimage_offscreen); */ CGContextSaveGState(myContext); #ifndef DRIVER_IOS // CGContextTranslateCTM(myContext,0.0, X_A2_WINDOW_HEIGHT); CGContextTranslateCTM(myContext,0.0, myBoundingBox.size.height); CGContextScaleCTM(myContext,1.0,-1.0); #endif CGImageRef myImage = CGBitmapContextCreateImage((CGContextRef)g_kimage_offscreen.dev_handle); CGContextDrawImage(myContext, myBoundingBox, myImage);// 6 #ifndef VIDEO_SINGLEVLINE if (r_sim65816.get_video_fx() == VIDEOFX_CRT) { CGContextSetRGBFillColor(myContext,0,0,0,0.5); for(int h=0;h<g_kimage_offscreen.height;h+=2) { CGRect r = CGRectMake(0,h,g_kimage_offscreen.width_act,1); CGContextFillRect(myContext,r); } } #endif CGImageRelease(myImage); CGContextRestoreGState(myContext); #ifndef DRIVER_IOS if (!messageLine.IsEmpty()) { CGContextSaveGState(myContext); CGContextSetTextMatrix(myContext,CGAffineTransformIdentity); CGContextTranslateCTM(myContext,0.0, X_A2_WINDOW_HEIGHT); CGContextScaleCTM(myContext,1.0,-1.0); CGContextSelectFont(myContext, "Courier", 14.0, kCGEncodingMacRoman); CGContextSetTextDrawingMode(myContext, kCGTextFill); CGContextSetRGBFillColor (myContext, 1,1, 1, 1); CGContextSetShouldAntialias(myContext, true); #define SHADOW 4.0 CGFloat myColorValues[] = {0.5, 0.5, 0.5, 1.0}; CGColorSpaceRef myColorSpace = CGColorSpaceCreateDeviceRGB ();// 9 CGColorRef myColor = CGColorCreate (myColorSpace, myColorValues); CGContextSetShadowWithColor(myContext, CGSizeMake(SHADOW, -SHADOW), 4, myColor //CGColorCreateGenericGray(0.5,1.0) ); CGContextShowTextAtPoint(myContext, 20.0, X_A2_WINDOW_HEIGHT-20.0, messageLine.c_str(), messageLine.GetLength()); CGContextRestoreGState(myContext); messageLineVBL--; if (messageLineVBL<0) messageLine.Empty(); else x_refresh_video(); } #endif } else { CGContextSaveGState(myContext); #if defined(DRIVER_IOS) // efface en noir si l'émulateur n'avait pas encore démarré (le cas sur 3GS) CGContextSetRGBFillColor (myContext, 0, 0, 0, 1); #else CGContextSetRGBFillColor (myContext, 0, 0, 1, 1); #endif CGContextFillRect (myContext, CGRectMake (0, 0, X_A2_WINDOW_WIDTH, X_A2_WINDOW_HEIGHT)); CGContextRestoreGState(myContext); } } else { #ifdef ENABLEQD CGrafPtr window_port = pEmu->window_port; Rect src_rect; Rect dest_rect; SetRect(&src_rect,0,0,704,462); SetRect(&dest_rect,0,0,704,462); if (pixmap_backbuffer) CopyBits( (BitMap *)(*pixmap_backbuffer), GetPortBitMapForCopyBits(window_port), &src_rect, &dest_rect, srcCopy, NULL); #endif } CHANGE_BORDER(1,0); if (r_sim65816.is_emulator_offscreen_available() && g_driver.x_handle_state_on_paint) g_driver.x_handle_state_on_paint(myBoundingBox.size.width,myBoundingBox.size.height); }
RetainPtr<CGImageRef> ShareableBitmap::makeCGImageCopy() { auto graphicsContext = createGraphicsContext(); RetainPtr<CGImageRef> image = adoptCF(CGBitmapContextCreateImage(graphicsContext->platformContext())); return image; }