Exemplo n.º 1
0
// Ok, a bit freaky coz we want non-premultipied alpha!
//
BBDataBuffer *BBLoadImageData( BBDataBuffer *buf,String path,Array<int> info ) {

    path=String( "data/" )+path;
    NSString *nspath=path.ToNSString();

    //This was apparently buggy in iOS2.x, but NO MORE?
    UIImage *uiimage=[ UIImage imageNamed:nspath ];
    if( !uiimage ) return 0;

    CGImageRef cgimage=uiimage.CGImage;

    int width=CGImageGetWidth( cgimage );
    int height=CGImageGetHeight( cgimage );
    int pitch=CGImageGetBytesPerRow( cgimage );
    int bpp=CGImageGetBitsPerPixel( cgimage );

    if( bpp!=24 && bpp!=32 ) return 0;

    CFDataRef cfdata=CGDataProviderCopyData( CGImageGetDataProvider( cgimage ) );
    unsigned char *src=(unsigned char*)CFDataGetBytePtr( cfdata );
    int srclen=(int)CFDataGetLength( cfdata );

    if( !buf->_New( width*height*4 ) ) return 0;

    unsigned char *dst=(unsigned char*)buf->WritePointer();

    int y;

    switch( bpp ) {
    case 24:
        for( y=0; y<height; ++y ) {
            for( int x=0; x<width; ++x ) {
                *dst++=*src++;
                *dst++=*src++;
                *dst++=*src++;
                *dst++=255;
            }
            src+=pitch-width*3;
        }
        break;
    case 32:
        for( y=0; y<height; ++y ) {
            memcpy( dst,src,width*4 );
            dst+=width*4;
            src+=pitch;
        }
        break;
    }

    if( info.Length()>0 ) info[0]=width;
    if( info.Length()>1 ) info[1]=height;

    CFRelease( cfdata );

    return buf;
}
Exemplo n.º 2
0
uint32_t UtilCG::Texture::LoadTexture(const char *const aPath)
{
    CFStringRef Path = CFStringCreateWithCString(kCFAllocatorDefault, aPath, kCFStringEncodingASCII);
    CFURLRef Url = CFURLCreateWithFileSystemPath(kCFAllocatorDefault, Path, kCFURLPOSIXPathStyle, false);
    CGImageSourceRef Source = CGImageSourceCreateWithURL(Url, NULL);
    
    CGImageRef pImage = CGImageSourceCreateImageAtIndex(Source, 0, NULL);
    if ( !pImage )
    {
        CFRelease(Url);
        CFRelease(Path);
        CFRelease(Source);
        return INVALID_HANDLE;
    }
    
    CGDataProviderRef pDataProvider = CGImageGetDataProvider(pImage);
    if ( pDataProvider )
    {
        size_t width = CGImageGetWidth(pImage);
        size_t height = CGImageGetHeight(pImage);
        //size_t bytesPerRow = CGImageGetBytesPerRow(pImage);
        //size_t bitsPerPixel = CGImageGetBitsPerPixel(pImage);
        //size_t bitsPerComponent = CGImageGetBitsPerComponent(pImage);
        CFDataRef DataRef = CGDataProviderCopyData(pDataProvider);
        const UInt8* pData = CFDataGetBytePtr(DataRef);
        
        uint32_t hTexID = 0;
        glGenTextures(1, &hTexID);
        glBindTexture(GL_TEXTURE_2D, hTexID);
        glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
        glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
        glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
        glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
        glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, (GLint)width, (GLint)height, 0, GL_RGBA, GL_UNSIGNED_BYTE, pData);
        glBindTexture(GL_TEXTURE_2D, 0);
        
        CFRelease(Url);
        CFRelease(Path);
        CFRelease(Source);
        CGImageRelease(pImage);
      //  CGDataProviderRelease(pDataProvider);
        return hTexID;
    }
    
    CFRelease(Url);
    CFRelease(Path);
    CFRelease(Source);
    CGImageRelease(pImage);
    CGDataProviderRelease(pDataProvider);
    
    return INVALID_HANDLE;
}
Exemplo n.º 3
0
void CGImageLuminanceSource::init (CGImageRef cgimage, int left, int top, int width, int height) {
    data_ = 0;
    image_ = cgimage;
    left_ = left;
    top_ = top;
    width_ = width;
    height_ = height;
    dataWidth_ = (int)CGImageGetWidth(image_);
    dataHeight_ = (int)CGImageGetHeight(image_);

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

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

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

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

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

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

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

    CGDataProviderRef provider = CGImageGetDataProvider(image_);
    data_ = CGDataProviderCopyData(provider);
}
Exemplo n.º 4
0
Image::Image(CGImageRef image) :
	_width(CGImageGetWidth(image)),
	_height(CGImageGetHeight(image)),
	_bitsPerComponent(CGImageGetBitsPerComponent(image)),
	_bytesPerRow(CGImageGetBytesPerRow(image)),
	_colorSpaceRef(CGImageGetColorSpace(image)),
	_bitmapInfo(CGImageGetBitmapInfo(image)),
	_pixels(new pixel3f[_width * _height]),
	_copy(new pixel3f[_width * _height])
{
	// Obtain mutable image data.
	CFDataRef data = CGDataProviderCopyData(CGImageGetDataProvider(image));
	_data = CFDataCreateMutableCopy(NULL, CFDataGetLength(data), data);
	
	// Release data from image.
	CFRelease(data);
}
Exemplo n.º 5
0
OSStatus GeneratePreviewForURL(void *thisInterface, QLPreviewRequestRef preview, CFURLRef url, CFStringRef contentTypeUTI, CFDictionaryRef options)
{
	CGDataProviderRef dataProvider = CGDataProviderCreateWithURL(url);
	if (!dataProvider) return -1;
	CFDataRef data = CGDataProviderCopyData(dataProvider);
	CGDataProviderRelease(dataProvider);
	if (!data) return -1;
	
	int width, height, channels;
	unsigned char* rgbadata = SOIL_load_image_from_memory(CFDataGetBytePtr(data), CFDataGetLength(data), &width, &height, &channels, SOIL_LOAD_RGBA);
	CFStringRef format=CFStringCreateWithBytes(NULL, CFDataGetBytePtr(data) + 0x54, 4, kCFStringEncodingASCII, false);
    CFRelease(data);
	if (!rgbadata) return -1;
	
	CGColorSpaceRef rgb = CGColorSpaceCreateDeviceRGB();
	CGContextRef context = CGBitmapContextCreate(rgbadata, width, height, 8, width * 4, rgb, kCGImageAlphaPremultipliedLast);
	SOIL_free_image_data(rgbadata);
	CGColorSpaceRelease(rgb);
	if (!context) return -1;

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

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

	context = QLPreviewRequestCreateContext(preview, CGSizeMake(width, height), true, properties);
	CGContextDrawImage(context, CGRectMake(0, 0, width, height), image);
	QLPreviewRequestFlushContext(preview, context);
	
	CGContextRelease(context);
	CFRelease(format);
	CFRelease(properties);
	
	return noErr;
}
Exemplo n.º 6
0
Boolean GetMetadataForURL(void* thisInterface, 
			   CFMutableDictionaryRef attributes, 
			   CFStringRef contentTypeUTI,
			   CFURLRef url)
{

	CGDataProviderRef dataProvider = CGDataProviderCreateWithURL(url);
	if (!dataProvider) return FALSE;
	CFDataRef data = CGDataProviderCopyData(dataProvider);
	CGDataProviderRelease(dataProvider);
	if (!data) return FALSE;
	
	const UInt8 *buf = CFDataGetBytePtr(data);
	int *height= ((int*) buf) + 3;
	int *width = ((int*) buf) + 4;
	int *pflags= ((int*) buf) + 20;

	CFStringRef format=NULL;
	if ((*pflags)&DDPF_FOURCC)
		format = CFStringCreateWithBytes(kCFAllocatorDefault, buf + 0x54, 4, kCFStringEncodingASCII, false);
	else if ((*pflags)&DDPF_RGB)
		format = (*pflags)&DDPF_ALPHAPIXELS ? CFSTR("RGBA") : CFSTR("RGB");
	if (format)
	{
		CFArrayRef codecs = CFArrayCreate(kCFAllocatorDefault, (const void **) &format, 1, &kCFTypeArrayCallBacks);
		CFDictionaryAddValue(attributes, kMDItemCodecs, codecs);
		CFRelease(format);
		CFRelease(codecs);
	}
	
	CFNumberRef cfheight = CFNumberCreate(kCFAllocatorDefault, kCFNumberIntType, height);
	CFDictionaryAddValue(attributes, kMDItemPixelHeight, cfheight);
	CFRelease(cfheight);
	
	CFNumberRef cfwidth = CFNumberCreate(kCFAllocatorDefault, kCFNumberIntType, width);
	CFDictionaryAddValue(attributes, kMDItemPixelWidth, cfwidth);
	CFRelease(cfwidth);

	CFRelease(data);
    return TRUE;
}
Exemplo n.º 7
0
CFDataRef copyImagePixels(CGImageRef image)
{
  return CGDataProviderCopyData(CGImageGetDataProvider(image));
}
Exemplo n.º 8
0
bool GraphicsContext3D::getImageData(Image* image,
                                     unsigned int format,
                                     unsigned int type,
                                     bool premultiplyAlpha,
                                     Vector<uint8_t>& outputVector)
{
    if (!image)
        return false;
    CGImageRef cgImage;
    RetainPtr<CGImageRef> decodedImage;
    if (image->data()) {
        ImageSource decoder(false);
        decoder.setData(image->data(), true);
        if (!decoder.frameCount())
            return false;
        decodedImage = decoder.createFrameAtIndex(0);
        cgImage = decodedImage.get();
    } else
        cgImage = image->nativeImageForCurrentFrame();
    if (!cgImage)
        return false;
    size_t width = CGImageGetWidth(cgImage);
    size_t height = CGImageGetHeight(cgImage);
    if (!width || !height)
        return false;
    size_t bitsPerComponent = CGImageGetBitsPerComponent(cgImage);
    size_t bitsPerPixel = CGImageGetBitsPerPixel(cgImage);
    if (bitsPerComponent != 8 && bitsPerComponent != 16)
        return false;
    if (bitsPerPixel % bitsPerComponent)
        return false;
    size_t componentsPerPixel = bitsPerPixel / bitsPerComponent;
    SourceDataFormat srcDataFormat = kSourceFormatRGBA8;
    AlphaOp neededAlphaOp = kAlphaDoNothing;
    switch (CGImageGetAlphaInfo(cgImage)) {
    case kCGImageAlphaPremultipliedFirst:
        // This path is only accessible for MacOS earlier than 10.6.4.
        // This is a special case for texImage2D with HTMLCanvasElement input,
        // in which case image->data() should be null.
        ASSERT(!image->data());
        if (!premultiplyAlpha)
            neededAlphaOp = kAlphaDoUnmultiply;
        switch (componentsPerPixel) {
        case 2:
            if (bitsPerComponent == 8)
                srcDataFormat = kSourceFormatAR8;
            else
                srcDataFormat = kSourceFormatAR16;
            break;
        case 4:
            if (bitsPerComponent == 8)
                srcDataFormat = kSourceFormatARGB8;
            else
                srcDataFormat = kSourceFormatARGB16;
            break;
        default:
            return false;
        }
        break;
    case kCGImageAlphaFirst:
        // This path is only accessible for MacOS earlier than 10.6.4.
        if (premultiplyAlpha)
            neededAlphaOp = kAlphaDoPremultiply;
        switch (componentsPerPixel) {
        case 1:
            if (bitsPerComponent == 8)
                srcDataFormat = kSourceFormatA8;
            else
                srcDataFormat = kSourceFormatA16;
            break;
        case 2:
            if (bitsPerComponent == 8)
                srcDataFormat = kSourceFormatAR8;
            else
                srcDataFormat = kSourceFormatAR16;
            break;
        case 4:
            if (bitsPerComponent == 8)
                srcDataFormat = kSourceFormatARGB8;
            else
                srcDataFormat = kSourceFormatARGB16;
            break;
        default:
            return false;
        }
        break;
    case kCGImageAlphaNoneSkipFirst:
        // This path is only accessible for MacOS earlier than 10.6.4.
        switch (componentsPerPixel) {
        case 2:
            if (bitsPerComponent == 8)
                srcDataFormat = kSourceFormatAR8;
            else
                srcDataFormat = kSourceFormatAR16;
            break;
        case 4:
            if (bitsPerComponent == 8)
                srcDataFormat = kSourceFormatARGB8;
            else
                srcDataFormat = kSourceFormatARGB16;
            break;
        default:
            return false;
        }
        break;
    case kCGImageAlphaPremultipliedLast:
        // This is a special case for texImage2D with HTMLCanvasElement input,
        // in which case image->data() should be null.
        ASSERT(!image->data());
        if (!premultiplyAlpha)
            neededAlphaOp = kAlphaDoUnmultiply;
        switch (componentsPerPixel) {
        case 2:
            if (bitsPerComponent == 8)
                srcDataFormat = kSourceFormatRA8;
            else
                srcDataFormat = kSourceFormatRA16;
            break;
        case 4:
            if (bitsPerComponent == 8)
                srcDataFormat = kSourceFormatRGBA8;
            else
                srcDataFormat = kSourceFormatRGBA16;
            break;
        default:
            return false;
        }
        break;
    case kCGImageAlphaLast:
        if (premultiplyAlpha)
            neededAlphaOp = kAlphaDoPremultiply;
        switch (componentsPerPixel) {
        case 1:
            if (bitsPerComponent == 8)
                srcDataFormat = kSourceFormatA8;
            else
                srcDataFormat = kSourceFormatA16;
            break;
        case 2:
            if (bitsPerComponent == 8)
                srcDataFormat = kSourceFormatRA8;
            else
                srcDataFormat = kSourceFormatRA16;
            break;
        case 4:
            if (bitsPerComponent == 8)
                srcDataFormat = kSourceFormatRGBA8;
            else
                srcDataFormat = kSourceFormatRGBA16;
            break;
        default:
            return false;
        }
        break;
    case kCGImageAlphaNoneSkipLast:
        switch (componentsPerPixel) {
        case 2:
            if (bitsPerComponent == 8)
                srcDataFormat = kSourceFormatRA8;
            else
                srcDataFormat = kSourceFormatRA16;
            break;
        case 4:
            if (bitsPerComponent == 8)
                srcDataFormat = kSourceFormatRGBA8;
            else
                srcDataFormat = kSourceFormatRGBA16;
            break;
        default:
            return false;
        }
        break;
    case kCGImageAlphaNone:
        switch (componentsPerPixel) {
        case 1:
            if (bitsPerComponent == 8)
                srcDataFormat = kSourceFormatR8;
            else
                srcDataFormat = kSourceFormatR16;
            break;
        case 3:
            if (bitsPerComponent == 8)
                srcDataFormat = kSourceFormatRGB8;
            else
                srcDataFormat = kSourceFormatRGB16;
            break;
        default:
            return false;
        }
        break;
    default:
        return false;
    }
    RetainPtr<CFDataRef> pixelData;
    pixelData.adoptCF(CGDataProviderCopyData(CGImageGetDataProvider(cgImage)));
    if (!pixelData)
        return false;
    const UInt8* rgba = CFDataGetBytePtr(pixelData.get());
    outputVector.resize(width * height * 4);
    unsigned int srcUnpackAlignment = 0;
    size_t bytesPerRow = CGImageGetBytesPerRow(cgImage);
    unsigned int padding = bytesPerRow - bitsPerPixel / 8 * width;
    if (padding) {
        srcUnpackAlignment = padding + 1;
        while (bytesPerRow % srcUnpackAlignment)
            ++srcUnpackAlignment;
    }
    bool rt = packPixels(rgba, srcDataFormat, width, height, srcUnpackAlignment,
                         format, type, neededAlphaOp, outputVector.data());
    return rt;
}
Exemplo n.º 9
0
void process_1_image (args cli_flags, char *files) {
	
	char *out_file_name = get_out_filename (files, cli_flags);
	
	if (file_exists (out_file_name)) {
		printf ("| Output file %s already exists. skipping... ", out_file_name);
		return;
	}
	
	// Origional Image Properties struct
	img_prop o = (img_prop) malloc (sizeof (image_properties));
	
	// set all the vales in the imapg properties struct to -1
	null_ip (o);
	
	// Create a data provider
	CGDataProviderRef source_image_provider = CGDataProviderCreateWithFilename (files);
	
	// Check for a null returned value
	if (source_image_provider == NULL) {
		
		// something went wrong 
		printf ("error: Couldn't create CGDataProvider from URL.\n"); 
		exit (0);
	}
	
	// get the information from the image exif here
	o->image_rot = get_exif_rot (source_image_provider);
	

	// Create the image in memory from the JPEG data
	CGImageRef source_image = CGImageCreateWithJPEGDataProvider (source_image_provider, NULL, no, kCGRenderingIntentDefault);
	
  /********************************************/
  /* Getting the colour space **/
  
  o->colorSpace = CGImageGetColorSpace(source_image);
  
  /********************************************/
  
	// populate the image info struct
	pop_img_props (source_image, o);
	
	// create a data provider from the decoded JPEG data
	CGDataProviderRef image_data_provider = CGImageGetDataProvider (source_image);
	
	// Create a pointer to the data section of the image in memory
	CFDataRef source_data_ptr = CGDataProviderCopyData (image_data_provider);

	// The vImage_Buffers we will use
	vImage_Buffer *vImage_source = (vImage_Buffer*) malloc (sizeof (vImage_Buffer));
	
	// Check for NULL
	if (NULL == vImage_source) {
		printf ("Cannot malloc vImage_source buffer\n");
		exit (0);
	}
	
	if (o->bits_ppixel == 24) {
		
		// convert from 24bit to 32bit by adding the alpha channel.
		source_data_ptr = convert24_32bit (source_data_ptr, o);
		
	}
	
	// Setup the vImage Buffer for the image
	setupBuffer (vImage_source, o->image_h, o->image_w, o->bytes_row);

	// Assign the data to the vImage Buffer for the source
	vImage_source->data = (void *) CFDataGetBytePtr (source_data_ptr);
	
	// Check for NULL
	if (vImage_source->data == NULL) 
		printf ("Unable to get the vimage.data pointer\n");

	if (o->image_rot != 1 && o->image_rot != 4 && o->image_rot != 2) // rotate the image
		rotate_image (vImage_source, o, NULL);
	
	// flip the image
	if (o->image_rot == 2  || o->image_rot == 4 || o->image_rot == 7 || o->image_rot == 5)
		flip_image (vImage_source, o, NULL);
	
  
	// Resize the images
	resize_image (vImage_source, o, cli_flags);

    // Create a colour space to be compared against
    CGColorSpaceRef rgb = CGColorSpaceCreateWithName(kCGColorSpaceSRGB);
    if (NULL == rgb) {
        fprintf(stderr, "Unable to create the reference colourspace.\n");
        exit(0);
    }
    
    // Convert the colourspace to RGB
    if (!CFEqual(rgb, o->colorSpace) && !cli_flags->disableCC) {
        vImage_source->data = convert_space(vImage_source->data, o->image_w, o->image_h);
        if (NULL == vImage_source->data) exit(0);
    }
    
    // release the reference colour space
    CGColorSpaceRelease(rgb);
    
	// save the image
	save_image (vImage_source, o, cli_flags->quality, out_file_name);
	
	// Release the source provider
	CGDataProviderRelease (source_image_provider);
	source_image_provider = NULL;
	
	// Release the source image
	CGImageRelease (source_image);
	source_image = NULL;
	
	free(source_data_ptr);
    
	// Free the filename created by get_out_filename ()
	free (out_file_name);
	out_file_name = NULL;
	
	// free the image properties
	free (o);
	o = NULL;
	
	// if there is info in the buffer
	if (vImage_source->data != NULL) {
		free (vImage_source->data);
		vImage_source->data = NULL;
	}
	
	// free the buffer
	free (vImage_source);
	vImage_source = NULL;

} // Process 1 image
Exemplo n.º 10
0
void myOperator_Do(CGPDFScannerRef s, void *info)
{
    // Check to see if this is an image or not.
    const char *name;
    CGPDFObjectRef xobject;
    CGPDFDictionaryRef dict;
    CGPDFStreamRef stream;
    CGPDFContentStreamRef cs = CGPDFScannerGetContentStream(s);
    
    // The Do operator takes a name. Pop the name off the
    // stack. If this fails then the argument to the 
    // Do operator is not a name and is therefore invalid!
    if(!CGPDFScannerPopName(s, &name)){
		fprintf(stderr, "Couldn't pop name off stack!\n"); 
		return;
    }
    // Get the resource with type "XObject" and the name
    // obtained from the stack.
    xobject = CGPDFContentStreamGetResource(cs, "XObject", name);
    if(!xobject){
		fprintf(stderr, "Couldn't get XObject with name %s\n", name);
		return;
    }

    // An XObject must be a stream so obtain the value from the xobject
    // as if it were a stream. If this fails, the PDF is malformed.
    if (!CGPDFObjectGetValue(xobject, kCGPDFObjectTypeStream, &stream)){
		fprintf(stderr, "XObject '%s' is not a stream!\n", name);
		return;
    }
    // Streams consist of a dictionary and the data associated
    // with the stream. This code only cares about the dictionary.
    dict = CGPDFStreamGetDictionary(stream);
    if(!dict){
		fprintf(stderr, 
			"Couldn't obtain dictionary from stream %s!\n", name);
		return;
    }
    // An XObject dict has a Subtype that indicates what kind it is.
    if(!CGPDFDictionaryGetName(dict, "Subtype", &name)){
		fprintf(stderr, "Couldn't get SubType of dictionary object!\n");
		return;
    }
	
	
    // This code is interested in the "Image" Subtype of an XObject.
    // Check whether this object has Subtype of "Image".
	printf("%s\n",name);
    if(strcmp(name, "Image") != 0){
		// The Subtype is not "Image" so this must be a form 
		// or other type of XObject.
		return;
    } else {
		CGPDFArrayRef colorSpaceArray;
		CGPDFDictionaryGetArray(dict,"ColorSpace" ,&colorSpaceArray);
		CGColorSpaceRef colorSpace=NULL;
		colorSpace=colorSpaceFromPDFArray(colorSpaceArray);
		
		CGPDFDataFormat format;
		const char *name = NULL, *colorSpaceName = NULL,*renderingIntentName = NULL;;
		CFDataRef data=CGPDFStreamCopyData(stream,&format);
		if (format == CGPDFDataFormatRaw){
			CGColorSpaceRef cgColorSpace;
			CGPDFInteger width, height, bps, spp;
			CGColorRenderingIntent renderingIntent;
			CGPDFBoolean interpolation = 0;
			CGDataProviderRef dataProvider = CGDataProviderCreateWithCFData(data);
			
			if (!CGPDFDictionaryGetInteger(dict, "Width", &width))
				return ;
			
			if (!CGPDFDictionaryGetInteger(dict, "Height", &height))
				return ;
			
			if (!CGPDFDictionaryGetInteger(dict, "BitsPerComponent", &bps))
				return ;
			
			if (!CGPDFDictionaryGetBoolean(dict, "Interpolate", &interpolation))
				interpolation = 0;
			
			if (!CGPDFDictionaryGetName(dict, "Intent", &renderingIntentName))
				renderingIntent = kCGRenderingIntentDefault;
			else{
				renderingIntent = kCGRenderingIntentDefault;
				//      renderingIntent = renderingIntentFromName(renderingIntentName);
			}
			
			if (CGPDFDictionaryGetArray(dict, "ColorSpace", &colorSpaceArray)) {
				cgColorSpace = CGColorSpaceCreateDeviceRGB();
				//      cgColorSpace = colorSpaceFromPDFArray(colorSpaceArray);
				spp = CGColorSpaceGetNumberOfComponents(cgColorSpace);
			} else if (CGPDFDictionaryGetName(dict, "ColorSpace", &colorSpaceName)) {
				if (strcmp(colorSpaceName, "DeviceRGB") == 0) {
					cgColorSpace = CGColorSpaceCreateDeviceRGB();
					//          CGColorSpaceCreateWithName(kCGColorSpaceGenericRGB);
					spp = 3;
				} else if (strcmp(colorSpaceName, "DeviceCMYK") == 0) {     
					cgColorSpace = CGColorSpaceCreateDeviceCMYK();
					//          CGColorSpaceCreateWithName(kCGColorSpaceGenericCMYK);
					spp = 4;
				} else if (strcmp(colorSpaceName, "DeviceGray") == 0) {
					cgColorSpace = CGColorSpaceCreateDeviceGray();
					//          CGColorSpaceCreateWithName(kCGColorSpaceGenericGray);
					spp = 1;
				} else if (bps == 1) { // if there's no colorspace entry, there's still one we can infer from bps
					cgColorSpace = CGColorSpaceCreateDeviceGray();
					//          colorSpace = NSDeviceBlackColorSpace;
					spp = 1;
				}
			}
			 CGFloat *decodeValues = NULL;
			decodeValues = decodeValuesFromImageDictionary(dict, cgColorSpace, bps);
			
			int rowBits = bps * spp * width;
			int rowBytes = rowBits / 8;
			// pdf image row lengths are padded to byte-alignment
			if (rowBits % 8 != 0)
				++rowBytes;
			CGImageRef sourceImage = CGImageCreate(width, height, bps, bps * spp, rowBytes, cgColorSpace, 0, dataProvider, decodeValues, interpolation, renderingIntent);
			CGDataProviderRelease(dataProvider);
			
			
			CGDataProviderRef dataProvider2 = CGImageGetDataProvider(sourceImage);
			CFDataRef data = CGDataProviderCopyData(dataProvider2);
			int fd;
			findex;
			char file[256];
			memset(file,0,sizeof(file));
			sprintf(file,"%d.jpg",findex);	   
			fd=open(file, O_RDWR|O_CREAT);
			write(fd, CFDataGetBytePtr(data), CFDataGetLength(data));
			findex++;
			close(fd);
			
			//[[NSImage alloc] initWithCGImage:sourceImage size:NSMakeSize(0, 0)];
		}else {
			int fd;
			findex;
			char file[256];
			memset(file,0,sizeof(file));
			sprintf(file,"%d.jpg",findex);	   
			fd=open(file, O_RDWR|O_CREAT);
			write(fd, CFDataGetBytePtr(data), CFDataGetLength(data));
			findex++;
			close(fd);
		}


		
	}

    
    // This is an Image so figure out what variety of image it is.
    checkImageType(dict, (MyDataScan *)info);
    
}
Exemplo n.º 11
0
MMBitmapRef copyMMBitmapFromDisplayInRect(MMRect rect)
{
#if defined(IS_MACOSX)

	size_t bytewidth;
	uint8_t bitsPerPixel, bytesPerPixel;
	uint8_t *buffer;

	CGDirectDisplayID displayID = CGMainDisplayID();

	//Replacement for CGDisplayBitsPerPixel. 
	CGDisplayModeRef mode = CGDisplayCopyDisplayMode(displayID);
	size_t depth = 0;
	
	CFStringRef pixEnc = CGDisplayModeCopyPixelEncoding(mode);
	if(CFStringCompare(pixEnc, CFSTR(IO32BitDirectPixels), kCFCompareCaseInsensitive) == kCFCompareEqualTo)
		depth = 32;
	else if(CFStringCompare(pixEnc, CFSTR(IO16BitDirectPixels), kCFCompareCaseInsensitive) == kCFCompareEqualTo)
		depth = 16;
	else if(CFStringCompare(pixEnc, CFSTR(IO8BitIndexedPixels), kCFCompareCaseInsensitive) == kCFCompareEqualTo)
		depth = 8;

	bitsPerPixel = (uint8_t) depth; 
	bytesPerPixel = bitsPerPixel / 8;
	/* Align width to padding. */
	bytewidth = ADD_PADDING(rect.size.width * bytesPerPixel);

	/* Convert Quartz point to postscript point. */
	rect.origin.y = CGDisplayPixelsHigh(displayID) - rect.origin.y - rect.size.height;

	CGImageRef image = CGDisplayCreateImageForRect(displayID, CGRectMake(rect.origin.x, rect.origin.y, rect.size.width, rect.size.height));

    // Request access to the raw pixel data via the image's DataProvider.
    CGDataProviderRef provider = CGImageGetDataProvider(image);
    CFDataRef data = CGDataProviderCopyData(provider);

    size_t width, height;    
    width = CGImageGetWidth(image);
    height = CGImageGetHeight(image); 
    size_t bpp = CGImageGetBitsPerPixel(image) / 8;

    uint8 *pixels = malloc(width * height * bpp);
    memcpy(pixels, CFDataGetBytePtr(data), width * height * bpp);
    CFRelease(data); 
   	CGImageRelease(image); 

	return createMMBitmap(pixels, rect.size.width, rect.size.height, bytewidth,
	                      bitsPerPixel, bytesPerPixel);
#elif defined(USE_X11)
	MMBitmapRef bitmap;

	Display *display = XOpenDisplay(NULL);
	XImage *image = XGetImage(display,
	                          XDefaultRootWindow(display),
	                          (int)rect.origin.x,
	                          (int)rect.origin.y,
	                          (unsigned int)rect.size.width,
	                          (unsigned int)rect.size.height,
	                          AllPlanes, ZPixmap);
	XCloseDisplay(display);
	if (image == NULL) return NULL;

	bitmap = createMMBitmap((uint8_t *)image->data,
	                        rect.size.width,
	                        rect.size.height,
	                        (size_t)image->bytes_per_line,
	                        (uint8_t)image->bits_per_pixel,
	                        (uint8_t)image->bits_per_pixel / 8);
	image->data = NULL; /* Steal ownership of bitmap data so we don't have to
	                     * copy it. */
	XDestroyImage(image);

	return bitmap;
#elif defined(IS_WINDOWS)
	MMBitmapRef bitmap;
	void *data;
	HDC screen = NULL, screenMem = NULL;
	HBITMAP dib;
	BITMAPINFO bi;

	/* Initialize bitmap info. */
	bi.bmiHeader.biSize = sizeof(bi.bmiHeader);
   	bi.bmiHeader.biWidth = (long)rect.size.width;
   	bi.bmiHeader.biHeight = -(long)rect.size.height; /* Non-cartesian, please */
   	bi.bmiHeader.biPlanes = 1;
   	bi.bmiHeader.biBitCount = 32;
   	bi.bmiHeader.biCompression = BI_RGB;
   	bi.bmiHeader.biSizeImage = (DWORD)(4 * rect.size.width * rect.size.height);
	bi.bmiHeader.biXPelsPerMeter = 0;
	bi.bmiHeader.biYPelsPerMeter = 0;
	bi.bmiHeader.biClrUsed = 0;
	bi.bmiHeader.biClrImportant = 0;

	screen = GetDC(NULL); /* Get entire screen */
	if (screen == NULL) return NULL;

	/* Get screen data in display device context. */
   	dib = CreateDIBSection(screen, &bi, DIB_RGB_COLORS, &data, NULL, 0);

	/* Copy the data into a bitmap struct. */
	if ((screenMem = CreateCompatibleDC(screen)) == NULL ||
	    SelectObject(screenMem, dib) == NULL ||
	    !BitBlt(screenMem, 
	            (int)rect.origin.x, 
	            (int)rect.origin.y, 
	            (int)rect.size.width,
	            (int)rect.size.height, screen, 0, 0, SRCCOPY)) {
		/* Error copying data. */
		ReleaseDC(NULL, screen);
		DeleteObject(dib);
		if (screenMem != NULL) DeleteDC(screenMem);

		return NULL;
	}

	bitmap = createMMBitmap(NULL,
	                        rect.size.width,
	                        rect.size.height,
	                        4 * rect.size.width,
	                        (uint8_t)bi.bmiHeader.biBitCount, 
	                        4);

	/* Copy the data to our pixel buffer. */
	if (bitmap != NULL) {
		bitmap->imageBuffer = malloc(bitmap->bytewidth * bitmap->height);
		memcpy(bitmap->imageBuffer, data, bitmap->bytewidth * bitmap->height);
	}

	ReleaseDC(NULL, screen);
	DeleteObject(dib);
	DeleteDC(screenMem);

	return bitmap;
#endif
}