Пример #1
0
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;
    HWndDC dc(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);
    return hbmp;
}
Пример #2
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);
}
Пример #3
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;
    }
}
Пример #4
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;
}
Пример #5
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;
    }
}
Пример #6
0
static wxBitmap DoGetAsBitmap(const wxRect *subrect)
{
    CGRect cgbounds = CGDisplayBounds(CGMainDisplayID());

    wxRect rect = subrect ? *subrect : wxRect(0, 0, cgbounds.size.width, cgbounds.size.height);

    wxBitmap bmp(rect.GetSize().GetWidth(), rect.GetSize().GetHeight(), 32);

    CGDisplayCreateImageFunc createImage =
        (CGDisplayCreateImageFunc) dlsym(RTLD_NEXT, "CGDisplayCreateImage");
    if (createImage == NULL)
    {
        return bmp;
    }

    CGRect srcRect = CGRectMake(rect.x, rect.y, rect.width, rect.height);

    CGContextRef context = (CGContextRef)bmp.GetHBITMAP();

    CGContextSaveGState(context);

    CGContextTranslateCTM( context, 0,  cgbounds.size.height );
    CGContextScaleCTM( context, 1, -1 );

    if ( subrect )
        srcRect = CGRectOffset( srcRect, -subrect->x, -subrect->y ) ;

    CGImageRef image = NULL;

    image = createImage(kCGDirectMainDisplay);

    wxASSERT_MSG(image, wxT("wxScreenDC::GetAsBitmap - unable to get screenshot."));

    CGContextDrawImage(context, srcRect, image);

    CGImageRelease(image);

    CGContextRestoreGState(context);

    return bmp;
}
Пример #7
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());
}
Пример #8
0
void GraphicsContext3D::paintToCanvas(const unsigned char* imagePixels, int imageWidth, int imageHeight, int canvasWidth, int canvasHeight, CGContextRef context)
{
    if (!imagePixels || imageWidth <= 0 || imageHeight <= 0 || canvasWidth <= 0 || canvasHeight <= 0 || !context)
        return;
    int rowBytes = imageWidth * 4;
    RetainPtr<CGDataProviderRef> dataProvider(AdoptCF, CGDataProviderCreateWithData(0, imagePixels, rowBytes * imageHeight, 0));
    RetainPtr<CGColorSpaceRef> colorSpace(AdoptCF, CGColorSpaceCreateDeviceRGB());
    RetainPtr<CGImageRef> cgImage(AdoptCF, CGImageCreate(imageWidth, imageHeight, 8, 32, rowBytes, colorSpace.get(), kCGImageAlphaPremultipliedFirst | kCGBitmapByteOrder32Host,
        dataProvider.get(), 0, false, kCGRenderingIntentDefault));
    // CSS styling may cause the canvas's content to be resized on
    // the page. Go back to the Canvas to figure out the correct
    // width and height to draw.
    CGRect rect = CGRectMake(0, 0, canvasWidth, canvasHeight);
    // We want to completely overwrite the previous frame's
    // rendering results.
    CGContextSaveGState(context);
    CGContextSetBlendMode(context, kCGBlendModeCopy);
    CGContextSetInterpolationQuality(context, kCGInterpolationNone);
    CGContextDrawImage(context, rect, cgImage.get());
    CGContextRestoreGState(context);
}
Пример #9
0
bool GiCanvasIos::drawImage(CGImageRef image, const Box2d& rectM)
{
    CGContextRef context = m_draw->getContext();
    bool ret = false;
    
    if (context && image) {
        Point2d ptD = rectM.center() * m_draw->xf().modelToDisplay();
        Box2d rect = rectM * m_draw->xf().modelToDisplay();
        
        CGAffineTransform af = CGAffineTransformMake(1, 0, 0, -1, 0, m_draw->height());
        af = CGAffineTransformTranslate(af, ptD.x - rect.width() * 0.5f, 
                                        m_draw->height() - (ptD.y + rect.height() * 0.5f));
        
        CGContextConcatCTM(context, af);
        CGContextDrawImage(context, CGRectMake(0, 0, rect.width(), rect.height()), image);
        CGContextConcatCTM(context, CGAffineTransformInvert(af));
        ret = true;
    }
    
    return ret;
}
Пример #10
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;
}
Пример #11
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;
}
Пример #12
0
void DrawSubCGImage (CGContextRef ctx, CGImageRef image, CGRect src, CGRect dst)
{
    float	w = (float) CGImageGetWidth(image);
    float	h = (float) CGImageGetHeight(image);

	CGRect	drawRect = CGRectMake(0.0f, 0.0f, w, h);

	if (!CGRectEqualToRect(src, dst))
	{
		float	sx = CGRectGetWidth(dst)  / CGRectGetWidth(src);
		float	sy = CGRectGetHeight(dst) / CGRectGetHeight(src);
		float	dx = CGRectGetMinX(dst) - (CGRectGetMinX(src) * sx);
		float	dy = CGRectGetMinY(dst) - (CGRectGetMinY(src) * sy);

		drawRect = CGRectMake(dx, dy, w * sx, h * sy);
	}

	CGContextSaveGState(ctx);
	CGContextClipToRect(ctx, dst);
	CGContextDrawImage(ctx, drawRect, image);
	CGContextRestoreGState(ctx);
}
Пример #13
0
bool nglImageCGCodec::Feed(nglIStream* pIStream)
{
  if (!mpCGImage)
  {
    mpCGImage = ReadInfo(pIStream); ///< shall allocate the buffer
  }
  if (!mpCGImage)
    return false;

  mpIStream = pIStream;
// Use the generic RGB color space.
  CGColorSpaceRef pCGColors = CGColorSpaceCreateDeviceRGB();
  if (pCGColors == NULL)
  {
    NGL_OUT(_T("nglImageCGCodec::Feed Error allocating color space\n"));
    return false;
  }

  nglImageInfo info;
  mpImage->GetInfo(info);
  NGL_ASSERT(info.mpBuffer);

// Create the bitmap context. 
// The image will be converted to the format specified here by CGBitmapContextCreate.
  CGContextRef pCGContext =
    CGBitmapContextCreate(info.mpBuffer, info.mWidth, info.mHeight,
                          info.mBitDepth/4, info.mBytesPerLine,
                          pCGColors, kCGImageAlphaPremultipliedLast);//kCGImageAlphaPremultipliedFirst);

  CGColorSpaceRelease(pCGColors);
  CGRect rect = { {0,0}, {info.mWidth, info.mHeight} };
  CGContextClearRect(pCGContext, rect);
  CGContextDrawImage(pCGContext, rect, mpCGImage);
  CGContextRelease(pCGContext);

  SendData(1.0f);
  return (pIStream->GetState()==eStreamWait) || (pIStream->GetState()==eStreamReady);;
}
Пример #14
0
bool SkImageDecoder_CG::onDecode(SkStream* stream, SkBitmap* bm, Mode mode) {
    CGImageSourceRef imageSrc = SkStreamToCGImageSource(stream);

    if (NULL == imageSrc) {
        return false;
    }
    SkAutoTCallVProc<const void, CFRelease> arsrc(imageSrc);
    
    CGImageRef image = CGImageSourceCreateImageAtIndex(imageSrc, 0, NULL);
    if (NULL == image) {
        return false;
    }
    SkAutoTCallVProc<CGImage, CGImageRelease> arimage(image);
    
    const int width = CGImageGetWidth(image);
    const int height = CGImageGetHeight(image);
    bm->setConfig(SkBitmap::kARGB_8888_Config, width, height);
    if (SkImageDecoder::kDecodeBounds_Mode == mode) {
        return true;
    }
    
    if (!this->allocPixelRef(bm, NULL)) {
        return false;
    }
    
    bm->lockPixels();
    bm->eraseColor(0);

    // use the same colorspace, so we don't change the pixels at all
    CGColorSpaceRef cs = CGImageGetColorSpace(image);
    CGContextRef cg = CGBitmapContextCreate(bm->getPixels(), width, height,
                                            8, bm->rowBytes(), cs, BITMAP_INFO);
    CGContextDrawImage(cg, CGRectMake(0, 0, width, height), image);
    CGContextRelease(cg);

    bm->unlockPixels();
    return true;
}
Пример #15
0
DragImageRef createDragImageFromImage(Image* img)
{
    HBITMAP hbmp = 0;
    HDC dc = GetDC(0);
    HDC workingDC = CreateCompatibleDC(dc);
    CGContextRef drawContext = 0;
    if (!workingDC)
        goto exit;

    hbmp = allocImage(workingDC, img->size(), &drawContext);

    if (!hbmp)
        goto exit;

    if (!drawContext) {
        ::DeleteObject(hbmp);
        hbmp = 0;
    }

    CGImageRef srcImage = img->getCGImageRef();
    CGRect rect;
    rect.size = img->size();
    rect.origin.x = 0;
    rect.origin.y = -rect.size.height;
    static const CGFloat white [] = {1.0, 1.0, 1.0, 1.0};
    CGContextScaleCTM(drawContext, 1, -1);
    CGContextSetFillColor(drawContext, white);
    CGContextFillRect(drawContext, rect);
    CGContextSetBlendMode(drawContext, kCGBlendModeNormal);
    CGContextDrawImage(drawContext, rect, srcImage);
    CGContextRelease(drawContext);

exit:
    if (workingDC)
        DeleteDC(workingDC);
    ReleaseDC(0, dc);
    return hbmp;
}
Пример #16
0
cv::Mat CGImageToMat(CGImageRef image) {

  CGColorSpaceRef colorSpace = CGImageGetColorSpace(image);

  CGFloat cols = CGImageGetWidth(image);
  CGFloat rows = CGImageGetHeight(image);

  cv::Mat cvMat(rows, cols, CV_8UC4); // 8 bits per component, 4 channels (color channels + alpha)

  CGContextRef contextRef = CGBitmapContextCreate(cvMat.data,                 // Pointer to  data
						  cols,                       // Width of bitmap
						  rows,                       // Height of bitmap
						  8,                          // Bits per component
						  cvMat.step[0],              // Bytes per row
						  colorSpace,                 // Colorspace
						  kCGImageAlphaNoneSkipLast |
						  kCGBitmapByteOrderDefault); // Bitmap info flags

  CGContextDrawImage(contextRef, CGRectMake(0, 0, cols, rows), image);
  CGContextRelease(contextRef);

  return cvMat;
}
Пример #17
0
wxBitmap wxWindowDCImpl::DoGetAsBitmap(const wxRect *subrect) const
{
    // wxScreenDC is derived from wxWindowDC, so a screen dc will
    // call this method when a Blit is performed with it as a source.
    if (!m_window)
        return wxNullBitmap;

    ControlRef handle = (ControlRef) m_window->GetHandle();
    if ( !handle )
        return wxNullBitmap;

    HIRect rect;
    CGImageRef image;
    CGContextRef context;

    HIViewCreateOffscreenImage( handle, 0, &rect, &image);


    int width = subrect != NULL ? subrect->width : (int)rect.size.width;
    int height = subrect !=  NULL ? subrect->height : (int)rect.size.height ;

    wxBitmap bmp = wxBitmap(width, height, 32);

    context = (CGContextRef)bmp.GetHBITMAP();

    CGContextSaveGState(context);

    CGContextTranslateCTM( context, 0,  height );
    CGContextScaleCTM( context, 1, -1 );

    if ( subrect )
        rect = CGRectOffset( rect, -subrect->x, -subrect->y ) ;
    CGContextDrawImage( context, rect, image );

    CGContextRestoreGState(context);
    return bmp;
}
Пример #18
0
wxBitmap wxScreenDC::DoGetAsBitmap(const wxRect *subrect) const
{
#if wxMAC_USE_CORE_GRAPHICS
    CGRect srcRect = CGRectMake(0, 0, m_width, m_height);
    if (subrect)
    {
        srcRect.origin.x = subrect->GetX();
        srcRect.origin.y = subrect->GetY();
        srcRect.size.width = subrect->GetWidth();
        srcRect.size.height = subrect->GetHeight();
    }

    wxBitmap bmp = wxBitmap(srcRect.size.width, srcRect.size.height, 32);

    CGContextRef context = (CGContextRef)bmp.GetHBITMAP();

    CGContextSaveGState(context);

    CGContextTranslateCTM( context, 0,  m_height );
    CGContextScaleCTM( context, 1, -1 );

    if ( subrect )
        srcRect = CGRectOffset( srcRect, -subrect->x, -subrect->y ) ;

    CGImageRef image = grabViaOpenGL(kCGNullDirectDisplay, srcRect);

    wxASSERT_MSG(image, wxT("wxScreenDC::GetAsBitmap - unable to get screenshot."));

    CGContextDrawImage(context, srcRect, image);

    CGContextRestoreGState(context);

    return bmp;
#else
    return wxNullBitmap;
#endif
}
Пример #19
0
void ImageBuffer::putByteArray(Multiply multiplied, Uint8ClampedArray* source, const IntSize& sourceSize, const IntRect& sourceRect, const IntPoint& destPoint, CoordinateSystem coordinateSystem)
{
    if (!m_context->isAcceleratedContext()) {
        m_data.putData(source, sourceSize, sourceRect, destPoint, internalSize(), m_context->isAcceleratedContext(), multiplied == Unmultiplied, coordinateSystem == LogicalCoordinateSystem ? m_resolutionScale : 1);
        return;
    }

#if USE(IOSURFACE_CANVAS_BACKING_STORE)
    // Make a copy of the source to ensure the bits don't change before being drawn
    IntSize sourceCopySize(sourceRect.width(), sourceRect.height());
    OwnPtr<ImageBuffer> sourceCopy = ImageBuffer::create(sourceCopySize, 1, ColorSpaceDeviceRGB, Unaccelerated);
    if (!sourceCopy)
        return;

    sourceCopy->m_data.putData(source, sourceSize, sourceRect, IntPoint(-sourceRect.x(), -sourceRect.y()), sourceCopy->internalSize(), sourceCopy->context()->isAcceleratedContext(), multiplied == Unmultiplied, 1);

    // Set up context for using drawImage as a direct bit copy
    CGContextRef destContext = context()->platformContext();
    CGContextSaveGState(destContext);
    if (coordinateSystem == LogicalCoordinateSystem)
        CGContextConcatCTM(destContext, AffineTransform(wkGetUserToBaseCTM(destContext)).inverse());
    else
        CGContextConcatCTM(destContext, AffineTransform(CGContextGetCTM(destContext)).inverse());
    wkCGContextResetClip(destContext);
    CGContextSetInterpolationQuality(destContext, kCGInterpolationNone);
    CGContextSetAlpha(destContext, 1.0);
    CGContextSetBlendMode(destContext, kCGBlendModeCopy);
    CGContextSetShadowWithColor(destContext, CGSizeZero, 0, 0);

    // Draw the image in CG coordinate space
    IntPoint destPointInCGCoords(destPoint.x() + sourceRect.x(), (coordinateSystem == LogicalCoordinateSystem ? logicalSize() : internalSize()).height() - (destPoint.y() + sourceRect.y()) - sourceRect.height());
    IntRect destRectInCGCoords(destPointInCGCoords, sourceCopySize);
    RetainPtr<CGImageRef> sourceCopyImage(AdoptCF, sourceCopy->copyNativeImage());
    CGContextDrawImage(destContext, destRectInCGCoords, sourceCopyImage.get());
    CGContextRestoreGState(destContext);
#endif
}
Пример #20
0
CGImageRef CGImageMaskCreateWithImageRef(CGImageRef imageRef) {
  size_t maskWidth = CGImageGetWidth(imageRef);
  size_t maskHeight = CGImageGetHeight(imageRef);
  size_t bytesPerRow = maskWidth;
  size_t bufferSize = maskWidth * maskHeight;

  CFMutableDataRef dataBuffer = CFDataCreateMutable(kCFAllocatorDefault, 0);
  CFDataSetLength(dataBuffer, bufferSize);

  CGColorSpaceRef greyColorSpaceRef = CGColorSpaceCreateDeviceGray();
  CGContextRef ctx = CGBitmapContextCreate(CFDataGetMutableBytePtr(dataBuffer),
                                           maskWidth,
                                           maskHeight,
                                           8,
                                           bytesPerRow,
                                           greyColorSpaceRef,
                                           kCGImageAlphaNone);

  CGContextDrawImage(ctx, CGRectMake(0, 0, maskWidth, maskHeight), imageRef);
  CGContextRelease(ctx);

  CGDataProviderRef dataProvider = CGDataProviderCreateWithCFData(dataBuffer);
  CGImageRef maskImageRef = CGImageMaskCreate(maskWidth,
                                              maskHeight,
                                              8,
                                              8,
                                              bytesPerRow,
                                              dataProvider,
                                              NULL,
                                              FALSE);

  CGDataProviderRelease(dataProvider);
  CGColorSpaceRelease(greyColorSpaceRef);
  CFRelease(dataBuffer);

  return maskImageRef;
}
Пример #21
0
Screenshot* ScreenShooter::take_screenshot(const CFStringRef format, float compression) {
  CGImageRef* images = new CGImageRef[_dsp_count];
   
  /* Grab the images */
  for (unsigned int i = 0; i < _dsp_count; i++) {
     images[i] = CGDisplayCreateImage(_displays[i]);
  }

  /* Calculate size of image to produce */
  CGSize finalSize = CGSizeMake(_top_right.x - _bottom_left.x, _bottom_left.y - _top_right.y);

  /* Round out the bitmap size information */
  size_t bytesPerRow = finalSize.width * CGImageGetBitsPerPixel(images[0]) / 8;

  /* Create context around bitmap */
  CGContextRef context = CGBitmapContextCreate(
    NULL, finalSize.width, finalSize.height,
    CGImageGetBitsPerComponent(images[0]), bytesPerRow,
    CGImageGetColorSpace(images[0]), CGImageGetBitmapInfo(images[0])
  );

  /* Draw images into the bitmap */
  for (unsigned int i = 0; i < _dsp_count; i++)
  {
      /* Adjust the positions to account for coordinate system shifts
         (displays origin is at top left; image origin is at bottom left) */
      CGRect adjustedPoint = CGRectMake(_display_bounds[i].origin.x - _bottom_left.x,
                                        _bottom_left.y - _display_bounds[i].size.height - _display_bounds[i].origin.y,
                                        _display_bounds[i].size.width,
                                        _display_bounds[i].size.height);
      CGContextDrawImage(context, adjustedPoint, images[i]);
  }
  
  delete [] images;

  return new Screenshot(context, format, compression);
}
Пример #22
0
GLuint load_texure(const char *filename) {
	GLuint texid;

	// ImageIO loader
	CFStringRef path = CFStringCreateWithCString(NULL, filename, kCFStringEncodingUTF8);
	CFURLRef url = CFURLCreateWithFileSystemPath(NULL, path, kCFURLPOSIXPathStyle, 0);
	CGImageSourceRef imagesource = CGImageSourceCreateWithURL(url, NULL);
	CGImageRef image = CGImageSourceCreateImageAtIndex (imagesource, 0, NULL);
	size_t width = CGImageGetWidth(image);
	size_t height = CGImageGetHeight(image);
	CGRect rect = {{0, 0}, {width, height}};
	void * data = malloc(width * height * 4);
	CGColorSpaceRef space = CGColorSpaceCreateDeviceRGB();
	CGContextRef myBitmapContext = CGBitmapContextCreate (data, 
							width, height, 8,
							width*4, space, 
							kCGImageAlphaPremultipliedFirst);
	CGContextDrawImage(myBitmapContext, rect, image);
	CGContextRelease(myBitmapContext);
	CGColorSpaceRelease(space);
	CGImageRelease(image);
	CFRelease(imagesource);
	CFRelease(url);
	CFRelease(path);
	
	glGenTextures(1, &texid);
	glBindTexture(GL_TEXTURE_2D, texid);
	glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, width, height, 0, GL_BGRA_EXT, GL_UNSIGNED_INT_8_8_8_8_REV, data);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
	free(data);

	return texid;
}
Пример #23
0
bool GiCanvasIos::drawCachedBitmap(float x, float y, bool secondBmp)
{
    int index = secondBmp ? 1 : 0;
    CGImageRef image = m_draw->_cacheserr[index] ? NULL : m_draw->_caches[index];
    CGContextRef context = m_draw->getContext();
    bool ret = false;
    
    if (context && image) {
        CGRect rect = CGRectMake(x, y, m_draw->width(), m_draw->height());
        CGAffineTransform af = CGAffineTransformMake(1, 0, 0, -1, 0, m_draw->height());
        
        CGContextConcatCTM(context, af);    // 图像是朝上的,上下文坐标系朝下,上下颠倒显示
        
        CGInterpolationQuality oldQuality = CGContextGetInterpolationQuality(context);
        CGContextSetInterpolationQuality(context, kCGInterpolationNone);
        CGContextDrawImage(context, rect, image);
        CGContextSetInterpolationQuality(context, oldQuality);
        
        CGContextConcatCTM(context, CGAffineTransformInvert(af));   // 恢复成坐标系朝下
        ret = true;
    }
    
    return ret;
}
Пример #24
0
void CAUGuiGraphic::draw( CGContextRef context, UInt32 portHeight, eRect* r, float value )
{
	// if Image has frames, the frame will be drawn
	// otherwise, the plain image will get out
	
	CGRect bounds;
    
    CGContextSaveGState(context);
	
	if ( Frames > 1 )
	{
     
		r->to( &bounds, portHeight );
		
        CGContextClipToRect(context, bounds);
        
		SInt32 offset = (SInt32)((float)(Frames-1) * value) * r->h + r->h;
		
		SInt32 height = Frames * r->h;
		
		bounds.size.height = height;
		
		bounds.origin.y += offset-height;
	
	}
	else
	{
		r->to( &bounds, portHeight );
	}

	if ( Image != NULL )
			CGContextDrawImage( context, bounds, Image );

    CGContextRestoreGState(context);
    
}
Пример #25
0
static CGContextRef createCGContextFromImage(WKImageRef wkImage, FlipGraphicsContextOrNot flip = DontFlipGraphicsContext)
{
    RetainPtr<CGImageRef> image = adoptCF(WKImageCreateCGImage(wkImage));

    size_t pixelsWide = CGImageGetWidth(image.get());
    size_t pixelsHigh = CGImageGetHeight(image.get());
    size_t rowBytes = (4 * pixelsWide + 63) & ~63;

    // Creating this bitmap in the device color space should prevent any color conversion when the image of the web view is drawn into it.
    RetainPtr<CGColorSpaceRef> colorSpace = adoptCF(CGColorSpaceCreateDeviceRGB());
    CGContextRef context = CGBitmapContextCreate(0, pixelsWide, pixelsHigh, 8, rowBytes, colorSpace.get(), kCGImageAlphaPremultipliedFirst | kCGBitmapByteOrder32Host);
    
    if (flip == FlipGraphicsContext) {
        CGContextSaveGState(context);
        CGContextScaleCTM(context, 1, -1);
        CGContextTranslateCTM(context, 0, -static_cast<CGFloat>(pixelsHigh));
    }
    
    CGContextDrawImage(context, CGRectMake(0, 0, pixelsWide, pixelsHigh), image.get());
    if (flip == FlipGraphicsContext)
        CGContextRestoreGState(context);

    return context;
}
Пример #26
0
    bool GCPVideoRenderer::OnWindowRefresh(FB::RefreshEvent* pEvt)
    {
        FB::CoreGraphicsDraw* pCgDrawEvt(static_cast<FB::CoreGraphicsDraw*>(pEvt));
        CGContextRef pContext = pCgDrawEvt->context;
        boost::mutex::scoped_lock winLock(m_winMutex);

        const int stride = m_width*4;    
        const int frameBufferSize = m_height*stride;
        static SInt32 osMajorVersion = 0;
        static SInt32 osMinorVersion = 0;
        static CGInterpolationQuality interpolationMode = kCGInterpolationNone;
        
        if(0 == osMajorVersion || 0 == osMinorVersion)
        {
            if(noErr != Gestalt(gestaltSystemVersionMajor, &osMajorVersion))
            {
                osMajorVersion = 10;
            }
            if(noErr != Gestalt(gestaltSystemVersionMinor, &osMinorVersion))
            {
                osMinorVersion = 6;
            }
            if(10 <= osMajorVersion && 7 <= osMinorVersion)
            {
                interpolationMode = kCGInterpolationDefault;
            }
        }
        
        if(NULL == pContext || NULL == m_pFrameBuffer.get())
        {
            return false;
        }
        
        int winWidth = pCgDrawEvt->bounds.right - pCgDrawEvt->bounds.left;
        int winHeight = pCgDrawEvt->bounds.bottom - pCgDrawEvt->bounds.top;
        
        if(winWidth<=1 || winHeight<=1)
            return false;
        
        CGContextSaveGState(pContext);        
        CGContextSetShouldAntialias(pContext, true);
        CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
        CGImageRef cgImage = CGImageCreate(m_width, m_height, 8, 32, stride, colorSpace, 
                                           kCGImageAlphaNoneSkipLast,
                                           CGDataProviderCreateWithData(NULL,
                                                                        m_pFrameBuffer.get(),
                                                                        frameBufferSize,
                                                                        NULL),
                                           NULL, false, kCGRenderingIntentDefault);
        if(NULL == cgImage)
        {
            CGColorSpaceRelease(colorSpace);
            CGContextRestoreGState(pContext);
            return false;
        }
        
        CGContextSetInterpolationQuality(pContext, interpolationMode);
        CGContextTranslateCTM(pContext, 0, winHeight);
        CGContextScaleCTM(pContext, 1, -1);
        CGContextDrawImage(pContext, CGRectMake(0, 0, winWidth, winHeight), cgImage);
        
        CGImageRelease(cgImage);
        CGColorSpaceRelease(colorSpace);
        CGContextRestoreGState(pContext);
        
        return true;
    }
Пример #27
0
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);

}
Пример #28
0
static void drawPatternCallback(void* info, CGContextRef context)
{
    CGImageRef image = (CGImageRef)info;
    CGContextDrawImage(context, GraphicsContext(context).roundToDevicePixels(FloatRect(0, 0, CGImageGetWidth(image), CGImageGetHeight(image))), image);
}
Пример #29
0
/* Once we have our image (CGImageRef), we need to get it into an osg::Image */
osg::Image* CreateOSGImageFromCGImage(CGImageRef image_ref)
{
    /* This code is adapted from Apple's Documentation found here:
     * http://developer.apple.com/documentation/GraphicsImaging/Conceptual/OpenGL-MacProgGuide/index.html
     * Listing 9-4††Using a Quartz image as a texture source.
     * Unfortunately, this guide doesn't show what to do about
     * non-RGBA image formats so I'm making the rest up
     * (and it's probably all wrong).
     */

    size_t the_width = CGImageGetWidth(image_ref);
    size_t the_height = CGImageGetHeight(image_ref);
    CGRect the_rect = {{0, 0}, {the_width, the_height}};

    size_t bits_per_pixel = CGImageGetBitsPerPixel(image_ref);
    size_t bytes_per_row = CGImageGetBytesPerRow(image_ref);
//    size_t bits_per_component = CGImageGetBitsPerComponent(image_ref);
    size_t bits_per_component = 8;

    CGImageAlphaInfo alpha_info = CGImageGetAlphaInfo(image_ref);

    GLint internal_format;
    GLenum pixel_format;
    GLenum data_type;

    void* image_data = calloc(the_width * 4, the_height);

    CGColorSpaceRef color_space;
    CGBitmapInfo bitmap_info = CGImageGetBitmapInfo(image_ref);

    switch(bits_per_pixel)
    {
        // Drat, if 8-bit, how do you distinguish
        // between a 256 color GIF, a LUMINANCE map
        // or an ALPHA map?
        case 8:
        {
            // I probably did the formats all wrong for this case,
            // especially the ALPHA case.
            if(kCGImageAlphaNone == alpha_info)
            {
                /*
                 internal_format = GL_LUMINANCE;
                 pixel_format = GL_LUMINANCE;
                 */
                internal_format = GL_RGBA8;
                pixel_format = GL_BGRA_EXT;
                data_type = GL_UNSIGNED_INT_8_8_8_8_REV;

                bytes_per_row = the_width*4;
//                color_space = CGColorSpaceCreateWithName(kCGColorSpaceGenericRGB);
                color_space = CGColorSpaceCreateDeviceRGB();
//                bitmap_info = kCGImageAlphaPremultipliedFirst;
#if __BIG_ENDIAN__
                bitmap_info = kCGImageAlphaPremultipliedFirst | kCGBitmapByteOrder32Big; /* XRGB Big Endian */
#else
                bitmap_info = kCGImageAlphaPremultipliedFirst | kCGBitmapByteOrder32Little; /* XRGB Little Endian */
#endif
            }
            else
            {
                internal_format = GL_ALPHA;
                pixel_format = GL_ALPHA;
                data_type = GL_UNSIGNED_BYTE;
                //            bytes_per_row = the_width;
//                color_space = CGColorSpaceCreateWithName(kCGColorSpaceGenericGray);
                color_space = CGColorSpaceCreateDeviceGray();
            }

            break;
        }
        case 24:
        {
            internal_format = GL_RGBA8;
            pixel_format = GL_BGRA_EXT;
            data_type = GL_UNSIGNED_INT_8_8_8_8_REV;
            bytes_per_row = the_width*4;
//            color_space = CGColorSpaceCreateWithName(kCGColorSpaceGenericRGB);
            color_space = CGColorSpaceCreateDeviceRGB();
//            bitmap_info = kCGImageAlphaNone;
#if __BIG_ENDIAN__
            bitmap_info = kCGImageAlphaNoneSkipFirst | kCGBitmapByteOrder32Big; /* XRGB Big Endian */
#else
            bitmap_info = kCGImageAlphaNoneSkipFirst | kCGBitmapByteOrder32Little; /* XRGB Little Endian */
#endif
            break;
        }
        //
        // Tatsuhiro Nishioka
        // 16 bpp grayscale (8 bit white and 8 bit alpha) causes invalid argument combination
        // in CGBitmapContextCreate.
        // I guess it is safer to handle 16 bit grayscale image as 32-bit RGBA image.
        // It works at least on FlightGear
        //
        case 16:
        case 32:
        case 48:
        case 64:
        {

            internal_format = GL_RGBA8;
            pixel_format = GL_BGRA_EXT;
            data_type = GL_UNSIGNED_INT_8_8_8_8_REV;

            bytes_per_row = the_width*4;
//            color_space = CGColorSpaceCreateWithName(kCGColorSpaceGenericRGB);
            color_space = CGColorSpaceCreateDeviceRGB();
//            bitmap_info = kCGImageAlphaPremultipliedFirst;

#if __BIG_ENDIAN__
            bitmap_info = kCGImageAlphaPremultipliedFirst | kCGBitmapByteOrder32Big; /* XRGB Big Endian */
#else
            bitmap_info = kCGImageAlphaPremultipliedFirst | kCGBitmapByteOrder32Little; /* XRGB Little Endian */
#endif
            break;
        }
        default:
        {
            // OSG_WARN << "Unknown file type in " << fileName.c_str() << " with " << origDepth << std::endl;
            return NULL;
            break;
        }

    }
    

    // Sets up a context to be drawn to with image_data as the area to be drawn to
    CGContextRef bitmap_context = CGBitmapContextCreate(
        image_data,
        the_width,
        the_height,
        bits_per_component,
        bytes_per_row,
        color_space,
        bitmap_info
    );
    
    CGContextTranslateCTM(bitmap_context, 0, the_height);
    CGContextScaleCTM(bitmap_context, 1.0, -1.0);
    // Draws the image into the context's image_data
    CGContextDrawImage(bitmap_context, the_rect, image_ref);

    CGContextRelease(bitmap_context);
    
    if (!image_data)
        return NULL;

    // alpha is premultiplied with rgba, undo it
    
    vImage_Buffer vb;
    vb.data = image_data;
    vb.height = the_height;
    vb.width = the_width;
    vb.rowBytes = the_width * 4;
    vImageUnpremultiplyData_RGBA8888(&vb, &vb, 0);
    
    // changing it to GL_UNSIGNED_BYTE seems working, but I'm not sure if this is a right way.
    //
    data_type = GL_UNSIGNED_BYTE;
    osg::Image* osg_image = new osg::Image;

    osg_image->setImage(
        the_width,
        the_height,
        1,
        internal_format,
        pixel_format,
        data_type,
        (unsigned char*)image_data,
        osg::Image::USE_MALLOC_FREE // Assumption: osg_image takes ownership of image_data and will free
    );

    return osg_image;



}
Пример #30
0
bool CBaseTexture::LoadFromFile(const CStdString& texturePath, unsigned int maxWidth, unsigned int maxHeight,
                                bool autoRotate, unsigned int *originalWidth, unsigned int *originalHeight)
{
  if (URIUtils::GetExtension(texturePath).Equals(".dds"))
  { // special case for DDS images
    CDDSImage image;
    if (image.ReadFile(texturePath))
    {
      Update(image.GetWidth(), image.GetHeight(), 0, image.GetFormat(), image.GetData(), false);
      return true;
    }
    return false;
  }

#if defined(__APPLE__) && defined(__arm__)
  XFILE::CFile file;
  UInt8 *imageBuff      = NULL;
  int64_t imageBuffSize = 0;

  //open path and read data to buffer
  //this handles advancedsettings.xml pathsubstitution
  //and resulting networking
  if (file.Open(texturePath, 0))
  {
    imageBuffSize =file.GetLength();
    imageBuff = new UInt8[imageBuffSize];
    imageBuffSize = file.Read(imageBuff, imageBuffSize);
    file.Close();
  }
  else
  {
    CLog::Log(LOGERROR, "Texture manager unable to open file %s", texturePath.c_str());
    return false;
  }

  if (imageBuffSize <= 0)
  {
    CLog::Log(LOGERROR, "Texture manager read texture file failed.");
    delete [] imageBuff;
    return false;
  }

  // create the image from buffer;
  CGImageSourceRef imageSource;
  // create a CFDataRef using CFDataCreateWithBytesNoCopy and kCFAllocatorNull for deallocator.
  // this allows us to do a nocopy reference and we handle the free of imageBuff
  CFDataRef cfdata = CFDataCreateWithBytesNoCopy(NULL, imageBuff, imageBuffSize, kCFAllocatorNull);
  imageSource = CGImageSourceCreateWithData(cfdata, NULL);   
    
  if (imageSource == nil)
  {
    CLog::Log(LOGERROR, "Texture manager unable to load file: %s", CSpecialProtocol::TranslatePath(texturePath).c_str());
    CFRelease(cfdata);
    delete [] imageBuff;
    return false;
  }

  CGImageRef image = CGImageSourceCreateImageAtIndex(imageSource, 0, NULL);

  int rotate = 0;
  if (autoRotate)
  { // get the orientation of the image for displaying it correctly
    CFDictionaryRef imagePropertiesDictionary = CGImageSourceCopyPropertiesAtIndex(imageSource,0, NULL);
    if (imagePropertiesDictionary != nil)
    {
      CFNumberRef orientation = (CFNumberRef)CFDictionaryGetValue(imagePropertiesDictionary, kCGImagePropertyOrientation);
      if (orientation != nil)
      {
        int value = 0;
        CFNumberGetValue(orientation, kCFNumberIntType, &value);
        if (value)
          rotate = value - 1;
      }
      CFRelease(imagePropertiesDictionary);
    }
  }

  CFRelease(imageSource);

  unsigned int width  = CGImageGetWidth(image);
  unsigned int height = CGImageGetHeight(image);

  m_hasAlpha = (CGImageGetAlphaInfo(image) != kCGImageAlphaNone);

  if (originalWidth)
    *originalWidth = width;
  if (originalHeight)
    *originalHeight = height;

  // check texture size limits and limit to screen size - preserving aspectratio of image  
  if ( width > g_Windowing.GetMaxTextureSize() || height > g_Windowing.GetMaxTextureSize() )
  {
    float aspect;

    if ( width > height )
    {
      aspect = (float)width / (float)height;
      width  = g_Windowing.GetWidth();
      height = (float)width / (float)aspect;
    }
    else
    {
      aspect = (float)height / (float)width;
      height = g_Windowing.GetHeight();
      width  = (float)height / (float)aspect;
    }
    CLog::Log(LOGDEBUG, "Texture manager texture clamp:new texture size: %i x %i", width, height);
  }

  // use RGBA to skip swizzling
  Allocate(width, height, XB_FMT_RGBA8);
  m_orientation = rotate;
    
  CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();

  // hw convert jmpeg to RGBA
  CGContextRef context = CGBitmapContextCreate(m_pixels,
    width, height, 8, GetPitch(), colorSpace,
    kCGImageAlphaPremultipliedLast | kCGBitmapByteOrder32Big);

  CGColorSpaceRelease(colorSpace);

  // Flip so that it isn't upside-down
  //CGContextTranslateCTM(context, 0, height);
  //CGContextScaleCTM(context, 1.0f, -1.0f);
  #if MAC_OS_X_VERSION_MAX_ALLOWED < MAC_OS_X_VERSION_10_5
    CGContextClearRect(context, CGRectMake(0, 0, width, height));
  #else
    #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
    // (just a way of checking whether we're running in 10.5 or later)
    if (CGContextDrawLinearGradient == 0)
      CGContextClearRect(context, CGRectMake(0, 0, width, height));
    else
    #endif
      CGContextSetBlendMode(context, kCGBlendModeCopy);
  #endif
  //CGContextSetBlendMode(context, kCGBlendModeCopy);
  CGContextDrawImage(context, CGRectMake(0, 0, width, height), image);
  CGContextRelease(context);
  CGImageRelease(image);
  CFRelease(cfdata);
  delete [] imageBuff;
#else
  DllImageLib dll;
  if (!dll.Load())
    return false;

  ImageInfo image;
  memset(&image, 0, sizeof(image));

  unsigned int width = maxWidth ? std::min(maxWidth, g_Windowing.GetMaxTextureSize()) : g_Windowing.GetMaxTextureSize();
  unsigned int height = maxHeight ? std::min(maxHeight, g_Windowing.GetMaxTextureSize()) : g_Windowing.GetMaxTextureSize();

  if(!dll.LoadImage(texturePath.c_str(), width, height, &image))
  {
    CLog::Log(LOGERROR, "Texture manager unable to load file: %s", texturePath.c_str());
    return false;
  }

  m_hasAlpha = NULL != image.alpha;

  Allocate(image.width, image.height, XB_FMT_A8R8G8B8);
  if (autoRotate && image.exifInfo.Orientation)
    m_orientation = image.exifInfo.Orientation - 1;
  if (originalWidth)
    *originalWidth = image.originalwidth;
  if (originalHeight)
    *originalHeight = image.originalheight;

  unsigned int dstPitch = GetPitch();
  unsigned int srcPitch = ((image.width + 1)* 3 / 4) * 4; // bitmap row length is aligned to 4 bytes

  unsigned char *dst = m_pixels;
  unsigned char *src = image.texture + (m_imageHeight - 1) * srcPitch;

  for (unsigned int y = 0; y < m_imageHeight; y++)
  {
    unsigned char *dst2 = dst;
    unsigned char *src2 = src;
    for (unsigned int x = 0; x < m_imageWidth; x++, dst2 += 4, src2 += 3)
    {
      dst2[0] = src2[0];
      dst2[1] = src2[1];
      dst2[2] = src2[2];
      dst2[3] = 0xff;
    }
    src -= srcPitch;
    dst += dstPitch;
  }

  if(image.alpha)
  {
    dst = m_pixels + 3;
    src = image.alpha + (m_imageHeight - 1) * m_imageWidth;

    for (unsigned int y = 0; y < m_imageHeight; y++)
    {
      unsigned char *dst2 = dst;
      unsigned char *src2 = src;

      for (unsigned int x = 0; x < m_imageWidth; x++,  dst2+=4, src2++)
        *dst2 = *src2;
      src -= m_imageWidth;
      dst += dstPitch;
    }
  }
  dll.ReleaseImage(&image);
#endif

  ClampToEdge();

  return true;
}