bool ImageIODecoder::readHeader()
{
    CFURLRef         imageURLRef;
    CGImageSourceRef sourceRef;
    // diciu, if ReadHeader is called twice in a row make sure to release the previously allocated imageRef
    if (imageRef != NULL)
        CGImageRelease(imageRef);
    imageRef = NULL;

    imageURLRef = CFURLCreateFromFileSystemRepresentation( NULL,
        (const UInt8*)m_filename.c_str(), m_filename.size(), false );

    sourceRef = CGImageSourceCreateWithURL( imageURLRef, NULL );
    CFRelease( imageURLRef );
    if ( !sourceRef )
        return false;

    imageRef = CGImageSourceCreateImageAtIndex( sourceRef, 0, NULL );
    CFRelease( sourceRef );
    if( !imageRef )
        return false;

    m_width = CGImageGetWidth( imageRef );
    m_height = CGImageGetHeight( imageRef );

    CGColorSpaceRef colorSpace = CGImageGetColorSpace( imageRef );
    if( !colorSpace )
        return false;

    m_type = CGColorSpaceGetNumberOfComponents( colorSpace ) > 1 ? CV_8UC3 : CV_8UC1;

    return true;
}
/* Remember to CFRelease the created image when done. */
CGImageRef CreateCGImageFromFile(const char *the_path)
{
    CFURLRef         the_url    = NULL;
    CGImageRef       image_ref  = NULL;
    CGImageSourceRef source_ref = NULL;
    CFStringRef      cf_string  = NULL;

    /* Create a CFString from a C string */
    cf_string = CFStringCreateWithCString(
        NULL,
        the_path,
        kCFStringEncodingUTF8
        );
    if (!cf_string)
    {
        OSG_WARN << "CreateCGImageFromFile :: could not create CCFSTring" << std::endl;
        return NULL;
    }

    /* Create a CFURL from a CFString */
    the_url = CFURLCreateWithFileSystemPath(
        NULL,
        cf_string,
        kCFURLPOSIXPathStyle,
        false
        );

    /* Don't need the CFString any more (error or not) */
    CFRelease(cf_string);

    if (!the_url)
    {
        OSG_WARN << "CreateCGImageFromFile :: could not create CFUrl" << std::endl;
        return NULL;
    }


    source_ref = CGImageSourceCreateWithURL(the_url, NULL);
    /* Don't need the URL any more (error or not) */
    CFRelease(the_url);

    if (!source_ref)
    {
        OSG_WARN << "CreateCGImageFromFile :: could not create ImageSource" << std::endl;
        return NULL;
    }

    // Get the first item in the image source (some image formats may
    // contain multiple items).
    image_ref = CGImageSourceCreateImageAtIndex(source_ref, 0, NULL);
    if (!image_ref)
    {
        OSG_WARN << "CreateCGImageFromFile :: could not get Image" << std::endl;
    }

    /* Don't need the SourceRef any more (error or not) */
    CFRelease(source_ref);

    return image_ref;
}
예제 #3
0
파일: cgbitmap.cpp 프로젝트: DaniM/lyngo
//-----------------------------------------------------------------------------
bool CGBitmap::load (const CResourceDescription& desc)
{
	if (bits)
		return false;

	bool result = false;
	if (getBundleRef ())
	{
		// find the bitmap in our Bundle.
		// If the resource description is of type integer, it must be in the form of bmp00123.png, where the resource id would be 123.
		// else it just uses the name
		char filename [PATH_MAX];
		if (desc.type == CResourceDescription::kIntegerType)
			sprintf (filename, "bmp%05d", (int32_t)desc.u.id);
		else
			strcpy (filename, desc.u.name);
		CFStringRef cfStr = CFStringCreateWithCString (NULL, filename, kCFStringEncodingUTF8);
		if (cfStr)
		{
			CFURLRef url = NULL;
			if (filename[0] == '/')
				url = CFURLCreateFromFileSystemRepresentation (0, (const UInt8*)filename, strlen (filename), false);
			int32_t i = 0;
			while (url == NULL)
			{
				static CFStringRef resTypes [] = { CFSTR("png"), CFSTR("bmp"), CFSTR("jpg"), CFSTR("pict"), NULL };
				url = CFBundleCopyResourceURL (getBundleRef (), cfStr, desc.type == CResourceDescription::kIntegerType ? resTypes[i] : 0, NULL);
				if (resTypes[++i] == NULL)
					break;
			}
			CFRelease (cfStr);
			if (url)
			{
				CGImageSourceRef source = CGImageSourceCreateWithURL (url, NULL);
				if (source)
				{
					result = loadFromImageSource (source);
					CFRelease (source);
				}
				CFRelease (url);
			}
		}
	}
#if DEBUG
	if (result == false)
	{
		if (desc.type == CResourceDescription::kIntegerType)
			DebugPrint ("*** Bitmap Nr.:%d not found.\n", desc.u.id);
		else
			DebugPrint ("*** Bitmap '%s' not found.\n", desc.u.name);
	}
#endif
	return result;
}
예제 #4
0
파일: UtilCG.cpp 프로젝트: leezyli/LearnGL
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;
}
예제 #5
0
vl::Image
vl::ImageReader::readDimensions(const char * fileName)
{
  // intermediate buffer
  char unsigned * rgba = NULL ;

  // Core graphics
  CFURLRef url = NULL ;
  CGImageSourceRef imageSourceRef = NULL ;
  CGImageRef imageRef = NULL ;
  CGColorSpaceRef colorSpaceRef = NULL ;

  // initialize the image as null
  Image image ;
  image.width = 0 ;
  image.height = 0 ;
  image.depth = 0 ;
  image.memory = NULL ;
  image.error = 0 ;

  // get file
  url = CFURLCreateFromFileSystemRepresentation(kCFAllocatorDefault, (const UInt8 *)fileName, strlen(fileName), false) ;
  check(url) ;

  // get image source from file
  imageSourceRef = CGImageSourceCreateWithURL(url, NULL) ;
  check(imageSourceRef) ;

  // get image from image source
  imageRef = CGImageSourceCreateImageAtIndex(imageSourceRef, 0, NULL);
  check(imageRef) ;

  colorSpaceRef = CGColorSpaceCreateDeviceRGB();
  check(colorSpaceRef) ;

  image.width = CGImageGetWidth(imageRef);
  image.height = CGImageGetHeight(imageRef);
  image.depth = CGColorSpaceGetNumberOfComponents(colorSpaceRef) ;
  check(image.depth == 1 || image.depth == 3) ;

done:
  if (colorSpaceRef) { CFRelease(colorSpaceRef) ; }
  if (imageRef) { CFRelease(imageRef) ; }
  if (imageSourceRef) { CFRelease(imageSourceRef) ; }
  if (url) { CFRelease(url) ; }
  return image ;
}
예제 #6
0
/* Remember to CFRelease the created source when done. */
static CGImageSourceRef CreateCGImageSourceFromFile(const char* the_path)
{
    CFURLRef the_url = NULL;
    CGImageSourceRef source_ref = NULL;
	CFStringRef cf_string = NULL;
	
	/* Create a CFString from a C string */
	cf_string = CFStringCreateWithCString(
										  NULL,
										  the_path,
										  kCFStringEncodingUTF8
										  );
	if(!cf_string)
	{
		return NULL;
	}
	
	/* Create a CFURL from a CFString */
    the_url = CFURLCreateWithFileSystemPath(
											NULL, 
											cf_string,
											kCFURLPOSIXPathStyle,
											false
											);
	
	/* Don't need the CFString any more (error or not) */
	CFRelease(cf_string);
	
	if(!the_url)
	{
		return NULL;
	}
	
	
    source_ref = CGImageSourceCreateWithURL(the_url, NULL);
	/* Don't need the URL any more (error or not) */
	CFRelease(the_url);
	
	return source_ref;
}
예제 #7
0
파일: cgbitmap.cpp 프로젝트: DaniM/lyngo
//-----------------------------------------------------------------------------
IPlatformBitmap* IPlatformBitmap::createFromPath (UTF8StringPtr absolutePath)
{
	CGBitmap* bitmap = 0;
	CFURLRef url = CFURLCreateFromFileSystemRepresentation (0, (const UInt8*)absolutePath, strlen (absolutePath), false);
	if (url)
	{
		CGImageSourceRef source = CGImageSourceCreateWithURL (url, NULL);
		if (source)
		{
			bitmap = new CGBitmap ();
			bool result = bitmap->loadFromImageSource (source);
			if (result == false)
			{
				bitmap->forget ();
				bitmap = 0;
			}
			CFRelease (source);
		}
		CFRelease (url);
	}
	return bitmap;
}
예제 #8
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;
}
예제 #9
0
static void _GraphicsScreen_imageFromFile (GraphicsScreen me, const wchar_t *relativeFileName, double x1, double x2, double y1, double y2) {
	long x1DC = wdx (x1), x2DC = wdx (x2), y1DC = wdy (y1), y2DC = wdy (y2);
	long width = x2DC - x1DC, height = my yIsZeroAtTheTop ? y1DC - y2DC : y2DC - y1DC;
	#if 0
		structMelderFile file = { 0 };
		Melder_relativePathToFile (relativeFileName, & file);
		try {
			autoPhoto photo = Photo_readFromImageFile (& file);
			if (x1 == x2 && y1 == y2) {
				width = photo -> nx, x1DC -= width / 2, x2DC = x1DC + width;
				height = photo -> ny, y2DC -= height / 2, y1DC = y2DC + height;
			} else if (x1 == x2) {
				width = height * (double) photo -> nx / (double) photo -> ny;
				x1DC -= width / 2, x2DC = x1DC + width;
			} else if (y1 == y2) {
				height = width * (double) photo -> ny / (double) photo -> nx;
				y2DC -= height / 2, y1DC = y2DC + height;
			}
			autoNUMmatrix <double_rgbt> z (1, photo -> ny, 1, photo -> nx);
			for (long iy = 1; iy <= photo -> ny; iy ++) {
				for (long ix = 1; ix <= photo -> nx; ix ++) {
					z [iy] [ix]. red          = photo -> d_red          -> z [iy] [ix];
					z [iy] [ix]. green        = photo -> d_green        -> z [iy] [ix];
					z [iy] [ix]. blue         = photo -> d_blue         -> z [iy] [ix];
					z [iy] [ix]. transparency = photo -> d_transparency -> z [iy] [ix];
				}
			}
			_cellArrayOrImage (me, NULL, z.peek(), NULL,
				1, photo -> nx, x1DC, x2DC, 1, photo -> ny, y1DC, y2DC,
				0.0, 1.0,
				//wdx (my d_x1WC), wdx (my d_x2WC), wdy (my d_y1WC), wdy (my d_y2WC),   // in case of clipping
				LONG_MIN, LONG_MAX, LONG_MAX, LONG_MIN,   // in case of no clipping
				true);
		} catch (MelderError) {
			Melder_clearError ();
		}
	#elif win
		if (my d_useGdiplus) {
			structMelderFile file = { 0 };
			Melder_relativePathToFile (relativeFileName, & file);
			Gdiplus::Bitmap image (file. path);
			if (x1 == x2 && y1 == y2) {
				width = image. GetWidth (), x1DC -= width / 2, x2DC = x1DC + width;
				height = image. GetHeight (), y2DC -= height / 2, y1DC = y2DC + height;
			} else if (x1 == x2) {
				width = height * (double) image. GetWidth () / (double) image. GetHeight ();
				x1DC -= width / 2, x2DC = x1DC + width;
			} else if (y1 == y2) {
				height = width * (double) image. GetHeight () / (double) image. GetWidth ();
				y2DC -= height / 2, y1DC = y2DC + height;
			}
			Gdiplus::Graphics dcplus (my d_gdiGraphicsContext);
			Gdiplus::Rect rect (x1DC, y2DC, width, height);
			dcplus. DrawImage (& image, rect);
		} else {
		}
	#elif mac
		structMelderFile file = { 0 };
		Melder_relativePathToFile (relativeFileName, & file);
		char utf8 [500];
		Melder_wcsTo8bitFileRepresentation_inline (file. path, utf8);
		CFStringRef path = CFStringCreateWithCString (NULL, utf8, kCFStringEncodingUTF8);
		CFURLRef url = CFURLCreateWithFileSystemPath (NULL, path, kCFURLPOSIXPathStyle, false);
		CFRelease (path);
		CGImageSourceRef imageSource = CGImageSourceCreateWithURL (url, NULL);
		CFRelease (url);
		if (imageSource != NULL) {
			CGImageRef image = CGImageSourceCreateImageAtIndex (imageSource, 0, NULL);
			CFRelease (imageSource);
			if (image != NULL) {
				if (x1 == x2 && y1 == y2) {
					width = CGImageGetWidth (image), x1DC -= width / 2, x2DC = x1DC + width;
					height = CGImageGetHeight (image), y2DC -= height / 2, y1DC = y2DC + height;
				} else if (x1 == x2) {
					width = height * (double) CGImageGetWidth (image) / (double) CGImageGetHeight (image);
					x1DC -= width / 2, x2DC = x1DC + width;
				} else if (y1 == y2) {
					height = width * (double) CGImageGetHeight (image) / (double) CGImageGetWidth (image);
					y2DC -= height / 2, y1DC = y2DC + height;
				}
				GraphicsQuartz_initDraw (me);
				CGContextSaveGState (my d_macGraphicsContext);
                
                NSCAssert(my d_macGraphicsContext, @"nil context");

				CGContextTranslateCTM (my d_macGraphicsContext, 0, y1DC);
				CGContextScaleCTM (my d_macGraphicsContext, 1.0, -1.0);
				CGContextDrawImage (my d_macGraphicsContext, CGRectMake (x1DC, 0, width, height), image);
				CGContextRestoreGState (my d_macGraphicsContext);
				GraphicsQuartz_exitDraw (me);
				CGImageRelease (image);
			}
		}
	#endif
}
예제 #10
0
/* the error does not contain the filename as the caller already has it */
CoglBitmap *
_cogl_bitmap_from_file (const char  *filename,
			GError     **error)
{
  CFURLRef url;
  CGImageSourceRef image_source;
  CGImageRef image;
  int save_errno;
  CFStringRef type;
  size_t width, height, rowstride;
  uint8_t *out_data;
  CGColorSpaceRef color_space;
  CGContextRef bitmap_context;
  CoglBitmap *bmp;

  _COGL_GET_CONTEXT (ctx, NULL);

  g_assert (filename != NULL);
  g_assert (error == NULL || *error == NULL);

  url = CFURLCreateFromFileSystemRepresentation (NULL,
                                                 (guchar *) filename,
                                                 strlen (filename),
                                                 false);
  image_source = CGImageSourceCreateWithURL (url, NULL);
  save_errno = errno;
  CFRelease (url);

  if (image_source == NULL)
    {
      /* doesn't exist, not readable, etc. */
      g_set_error_literal (error,
                           COGL_BITMAP_ERROR,
                           COGL_BITMAP_ERROR_FAILED,
                           g_strerror (save_errno));
      return NULL;
    }

  /* Unknown images would be cleanly caught as zero width/height below, but try
   * to provide better error message
   */
  type = CGImageSourceGetType (image_source);
  if (type == NULL)
    {
      CFRelease (image_source);
      g_set_error_literal (error,
                           COGL_BITMAP_ERROR,
                           COGL_BITMAP_ERROR_UNKNOWN_TYPE,
                           "Unknown image type");
      return NULL;
    }

  CFRelease (type);

  image = CGImageSourceCreateImageAtIndex (image_source, 0, NULL);
  CFRelease (image_source);

  width = CGImageGetWidth (image);
  height = CGImageGetHeight (image);
  if (width == 0 || height == 0)
    {
      /* incomplete or corrupt */
      CFRelease (image);
      g_set_error_literal (error,
                           COGL_BITMAP_ERROR,
                           COGL_BITMAP_ERROR_CORRUPT_IMAGE,
                           "Image has zero width or height");
      return NULL;
    }

  /* allocate buffer big enough to hold pixel data */
  bmp = _cogl_bitmap_new_with_malloc_buffer (ctx,
                                             width, height,
                                             COGL_PIXEL_FORMAT_ARGB_8888);
  rowstride = cogl_bitmap_get_rowstride (bmp);
  out_data = _cogl_bitmap_map (bmp,
                               COGL_BUFFER_ACCESS_WRITE,
                               COGL_BUFFER_MAP_HINT_DISCARD);

  /* render to buffer */
  color_space = CGColorSpaceCreateWithName (kCGColorSpaceGenericRGB);
  bitmap_context = CGBitmapContextCreate (out_data,
                                          width, height, 8,
                                          rowstride, color_space,
                                          kCGImageAlphaPremultipliedFirst);
  CGColorSpaceRelease (color_space);

  {
    const CGRect rect = {{0, 0}, {width, height}};

    CGContextDrawImage (bitmap_context, rect, image);
  }

  CGImageRelease (image);
  CGContextRelease (bitmap_context);

  _cogl_bitmap_unmap (bmp);

  /* store bitmap info */
  return bmp;
}
예제 #11
0
/* the error does not contain the filename as the caller already has it */
gboolean
_cogl_bitmap_from_file (CoglBitmap  *bmp,
			const gchar *filename,
			GError     **error)
{
  g_assert (bmp != NULL);
  g_assert (filename != NULL);
  g_assert (error == NULL || *error == NULL);

  CFURLRef url = CFURLCreateFromFileSystemRepresentation (NULL, (guchar*)filename, strlen(filename), false);
  CGImageSourceRef image_source = CGImageSourceCreateWithURL (url, NULL);
  int save_errno = errno;
  CFRelease (url);
  if (image_source == NULL)
    {
      /* doesn't exist, not readable, etc. */
      g_set_error (error, COGL_BITMAP_ERROR, COGL_BITMAP_ERROR_FAILED,
                   "%s", g_strerror (save_errno));
      return FALSE;
    }

  /* Unknown images would be cleanly caught as zero width/height below, but try
   * to provide better error message
   */
  CFStringRef type = CGImageSourceGetType (image_source);
  if (type == NULL)
    {
      CFRelease (image_source);
      g_set_error (error, COGL_BITMAP_ERROR, COGL_BITMAP_ERROR_UNKNOWN_TYPE,
                   "Unknown image type");
      return FALSE;
    }
  CFRelease (type);

  CGImageRef image = CGImageSourceCreateImageAtIndex (image_source, 0, NULL);
  CFRelease (image_source);

  size_t width = CGImageGetWidth (image);
  size_t height = CGImageGetHeight (image);
  if (width == 0 || height == 0)
    {
      /* incomplete or corrupt */
      CFRelease (image);
      g_set_error (error, COGL_BITMAP_ERROR, COGL_BITMAP_ERROR_CORRUPT_IMAGE,
                   "Image has zero width or height");
      return FALSE;
    }

  /* allocate buffer big enough to hold pixel data */
  size_t rowstride;
  CGBitmapInfo bitmap_info = CGImageGetBitmapInfo (image);
  if ((bitmap_info & kCGBitmapAlphaInfoMask) == kCGImageAlphaNone)
    {
      bitmap_info = kCGImageAlphaNone;
      rowstride = 3 * width;
    }
  else
    {
      bitmap_info = kCGImageAlphaPremultipliedFirst;
      rowstride = 4 * width;
    }
  guint8 *out_data = g_malloc0 (height * rowstride);

  /* render to buffer */
  CGColorSpaceRef color_space = CGColorSpaceCreateWithName (kCGColorSpaceGenericRGB);
  CGContextRef bitmap_context = CGBitmapContextCreate (out_data,
                                                       width, height, 8,
                                                       rowstride, color_space,
                                                       bitmap_info);
  CGColorSpaceRelease (color_space);

  const CGRect rect = {{0, 0}, {width, height}};
  CGContextDrawImage (bitmap_context, rect, image);

  CGImageRelease (image);
  CGContextRelease (bitmap_context);

  /* store bitmap info */
  bmp->data = out_data;
  bmp->format = bitmap_info == kCGImageAlphaPremultipliedFirst
                ? COGL_PIXEL_FORMAT_ARGB_8888
                : COGL_PIXEL_FORMAT_RGB_888;
  bmp->width = width;
  bmp->height = height;
  bmp->rowstride = rowstride;

  return TRUE;
}
/* read image file */
int BIReadFile(
	const char			*fileName,
	BIFileType			fileType,
	BIPadMode			padMode,
	unsigned			padSize,
	BIImageInfo			*imageInfo,		/* RETURNED */
	unsigned char		**bitmap)		/* mallocd and RETURNED; caller must free */
{
	CFURLRef fileURL = CFURLCreateFromFileSystemRepresentation(kCFAllocatorDefault, 
		(unsigned char*)fileName, strlen(fileName), FALSE);
	if(fileURL == NULL) {
		fprintf(stderr, "***BIReadFile: Error on CFURLCreateFromFileSystemRepresentation\n");
		return -1;
	}

	CFStringRef keys[1] = {kCGImageSourceTypeIdentifierHint};
	CFStringRef values[1] = {BIGetUTI(fileURL, fileType)};
	
	if(values[0] == NULL) {
		return -1;
	}
	
	CFDictionaryRef		optionsDict = NULL;
	CGImageSourceRef	imageSourceRef = NULL;
	CGImageRef			imageRef = NULL;
	CGColorSpaceRef		rgbColorSpaceRef = NULL;
	CGContextRef		bitmapContextRef = NULL;
	CGBitmapInfo		bitmapInfo = 0;
	CGImageAlphaInfo	alpha;
	unsigned			bytesPerPixel = 4;
	
	optionsDict = CFDictionaryCreate( kCFAllocatorDefault, 
		(const void **)keys, (const void **)values, 1,  
		&kCFTypeDictionaryKeyCallBacks,  &kCFTypeDictionaryValueCallBacks );
	/* subsequent errors to errOut: */
	
	int ourRtn = 0;
	
	/* source file --> CGImageRef */
	imageSourceRef = CGImageSourceCreateWithURL(fileURL, optionsDict);
	if(imageSourceRef == NULL) {
		fprintf(stderr, "***BIReadFile: Error on CGImageSourceCreateWithURL\n");
		ourRtn = 1;
		goto errOut;
	}
	CFRELEASE(fileURL);
	imageRef = CGImageSourceCreateImageAtIndex(imageSourceRef, 0, optionsDict );
	if(imageRef == NULL) {
		fprintf(stderr, "***BIReadFile: Error on CGImageSourceCreateImageAtIndex\n");
		ourRtn = 1;
		goto errOut;
	}
	
	imageInfo->imageWidth			= CGImageGetWidth(imageRef);
	imageInfo->imageHeight			= CGImageGetHeight(imageRef);
	imageInfo->bitsPerComponent		= CGImageGetBitsPerComponent(imageRef);
	imageInfo->bitsPerPixel			= CGImageGetBitsPerPixel(imageRef);
	
	if(imageInfo->bitsPerPixel == 8) {
		/* the image is gray */
		rgbColorSpaceRef = CGColorSpaceCreateWithName(kCGColorSpaceGenericGray);
		imageInfo->bytesPerRow = imageInfo->imageWidth; 
		alpha = kCGImageAlphaNone;
		bitmapInfo = CGImageGetBitmapInfo(imageRef);
		bytesPerPixel = 1;
	}
	else {
        rgbColorSpaceRef = CGColorSpaceCreateDeviceRGB();
		imageInfo->bytesPerRow = imageInfo->imageWidth * 4;
		alpha = kCGImageAlphaPremultipliedLast;
		bitmapInfo = kCGBitmapByteOrder32Big | alpha;
	}
	if(rgbColorSpaceRef == NULL) {
		fprintf(stderr, "***BIReadFile: Error on CGColorSpaceCreateWithName\n");
		ourRtn = 1;
		goto errOut;
	}
	
	/* optionally pad */
	imageInfo->effectHeight = imageInfo->imageHeight;
	if(padMode != PM_None) {
		if(padSize == 0) {
			fprintf(stderr, "***Pad size of 0 invalid\n");
			ourRtn = 1;
			goto errOut;
		}
		unsigned padSizeBytes = padSize;
		if(padMode == PM_Pixels) {
			padSizeBytes *= bytesPerPixel;
		}
		imageInfo->bytesPerRow = ROUND_TO(imageInfo->bytesPerRow, padSizeBytes);
		/* also round up row count */
		imageInfo->effectHeight = ROUND_TO(imageInfo->imageHeight, padSize);
	}

	*bitmap = (unsigned char *)malloc(imageInfo->bytesPerRow * imageInfo->effectHeight);
	
	bitmapContextRef = CGBitmapContextCreate(*bitmap, 
		imageInfo->imageWidth, imageInfo->imageHeight, 
		imageInfo->bitsPerComponent, imageInfo->bytesPerRow, 
		rgbColorSpaceRef, 
		bitmapInfo);
	if(bitmapContextRef == NULL) {
		fprintf(stderr, "***BIReadFile: Error creating CGBitmapContext\n");
		ourRtn = 1;
		goto errOut;
	}

	/* enable high quality interpolation */
	CGContextSetInterpolationQuality(bitmapContextRef, kCGInterpolationHigh);

	/* Draw into the context */
	CGContextDrawImage(bitmapContextRef, CGRectMake(0, 0, imageInfo->imageWidth, imageInfo->imageHeight), 
		imageRef);

errOut:
	CFRELEASE(optionsDict);
	CFRELEASE(imageSourceRef);
	CFRELEASE(imageRef);
	CFRELEASE(rgbColorSpaceRef);
	CFRELEASE(bitmapContextRef);
	if(ourRtn) {
		if(*bitmap) {
			free(*bitmap);
			*bitmap = NULL;
		}
	}
	return ourRtn;
}
예제 #13
0
vl::Image
vl::ImageReader::read(const char * fileName, float * memory)
{
  // intermediate buffer
  char unsigned * pixels = NULL ;
  int bytesPerPixel ;
  int bytesPerRow ;

  // Core graphics
  CGBitmapInfo bitmapInfo ;
  CFURLRef url = NULL ;
  CGImageSourceRef imageSourceRef = NULL ;
  CGImageRef imageRef = NULL ;
  CGContextRef contextRef = NULL ;
  CGColorSpaceRef sourceColorSpaceRef = NULL ;
  CGColorSpaceRef colorSpaceRef = NULL ;

  // initialize the image as null
  Image image ;
  image.width = 0 ;
  image.height = 0 ;
  image.depth = 0 ;
  image.memory = NULL ;
  image.error = 0 ;

  // get file
  url = CFURLCreateFromFileSystemRepresentation(kCFAllocatorDefault, (const UInt8 *)fileName, strlen(fileName), false) ;
  check(url) ;

  // get image source from file
  imageSourceRef = CGImageSourceCreateWithURL(url, NULL) ;
  check(imageSourceRef) ;

  // get image from image source
  imageRef = CGImageSourceCreateImageAtIndex(imageSourceRef, 0, NULL);
  check(imageRef) ;

  sourceColorSpaceRef = CGImageGetColorSpace(imageRef) ;
  check(sourceColorSpaceRef) ;

  image.width = CGImageGetWidth(imageRef);
  image.height = CGImageGetHeight(imageRef);
  image.depth = CGColorSpaceGetNumberOfComponents(sourceColorSpaceRef) ;
  check(image.depth == 1 || image.depth == 3) ;

  // decode image to L (8 bits per pixel) or RGBA (32 bits per pixel)
  switch (image.depth) {
    case 1:
      colorSpaceRef = CGColorSpaceCreateDeviceGray();
      bytesPerPixel = 1 ;
      bitmapInfo = kCGImageAlphaNone ;
      break ;

    case 3:
      colorSpaceRef = CGColorSpaceCreateDeviceRGB();
      bytesPerPixel = 4 ;
      bitmapInfo = kCGImageAlphaPremultipliedLast || kCGBitmapByteOrder32Big ;
      /* this means
       pixels[0] = R
       pixels[1] = G
       pixels[2] = B
       pixels[3] = A
       */
      break ;

  }
  check(colorSpaceRef) ;

  bytesPerRow = image.width * bytesPerPixel ;
  pixels = (char unsigned*)malloc(image.height * bytesPerRow) ;
  check(pixels) ;

  contextRef = CGBitmapContextCreate(pixels,
                                     image.width, image.height,
                                     8, bytesPerRow,
                                     colorSpaceRef,
                                     bitmapInfo) ;
  check(contextRef) ;

  CGContextDrawImage(contextRef, CGRectMake(0, 0, image.width, image.height), imageRef);

  // copy pixels to MATLAB format
  if (memory == NULL) {
    image.memory = (float*)malloc(image.height * image.width * image.depth * sizeof(float)) ;
    check(image.memory) ;
  } else {
    image.memory = memory ;
  }
  switch (image.depth) {
    case 3:
      vl::impl::imageFromPixels<impl::pixelFormatRGBA>(image, pixels, image.width * bytesPerPixel) ;
      break ;
    case 1:
      vl::impl::imageFromPixels<impl::pixelFormatL>(image, pixels, image.width * bytesPerPixel) ;
      break ;
  }

done:
  if (pixels) { free(pixels) ; }
  if (contextRef) { CFRelease(contextRef) ; }
  if (colorSpaceRef) { CFRelease(colorSpaceRef) ; }
  if (imageRef) { CFRelease(imageRef) ; }
  if (imageSourceRef) { CFRelease(imageSourceRef) ; }
  if (url) { CFRelease(url) ; }
  return image ;
}
예제 #14
0
CGImageSourceRef CGImageSourceCreateWithURL_wrap(u_char* bytes, uint32 len) {
  return CGImageSourceCreateWithURL(CFURLCreateWithBytes( kCFAllocatorDefault, bytes, len, kCFStringEncodingMacRoman, NULL), NULL);
}