Esempio n. 1
0
FIBITMAP *GraphicsHelps::loadImageRC(const char *file)
{
    unsigned char *memory = nullptr;
    size_t fileSize = 0;
    SDL_assert_release(RES_getMem(file, memory, fileSize));
    //{
        //pLogCritical("Resource file \"%s\" is not found!", file);
        //return nullptr;
    //}

    FIMEMORY *imgMEM = FreeImage_OpenMemory(memory, static_cast<FI_DWORD>(fileSize));
    FREE_IMAGE_FORMAT formato = FreeImage_GetFileTypeFromMemory(imgMEM);

    if(formato == FIF_UNKNOWN)
        return nullptr;

    FIBITMAP *img = FreeImage_LoadFromMemory(formato, imgMEM, 0);
    FreeImage_CloseMemory(imgMEM);

    if(!img)
        return nullptr;

    FIBITMAP *temp;
    temp = FreeImage_ConvertTo32Bits(img);

    if(!temp)
        return nullptr;

    FreeImage_Unload(img);
    img = temp;
    return img;
}
Esempio n. 2
0
FREE_IMAGE_FORMAT fipMemoryIO::getFileType() const {
	if(_hmem != NULL) {
		return FreeImage_GetFileTypeFromMemory(_hmem, 0);
	}

	return FIF_UNKNOWN;
}
Ogre::TexturePtr textureFromBytes(const QByteArray &ba,
                                  const std::string &name) {

  static bool fi_init = false;
  if (!fi_init) {
    FreeImage_Initialise();
  }

  void *data = const_cast<char *>(ba.data());
  FIMEMORY *mem =
      FreeImage_OpenMemory(reinterpret_cast<BYTE *>(data), ba.size());
  FREE_IMAGE_FORMAT fif = FreeImage_GetFileTypeFromMemory(mem, 0);
  if (fif == FIF_UNKNOWN) {
    FreeImage_CloseMemory(mem);
    throw std::runtime_error("Image format is not supported for loading");
  }
  FIBITMAP *bmp = FreeImage_LoadFromMemory(fif, mem, 0);
  FreeImage_CloseMemory(mem);
  if (!bmp) {
    throw std::runtime_error("Failed to decode image");
  }
  FIBITMAP *converted = FreeImage_ConvertTo24Bits(bmp);
  FreeImage_Unload(bmp);
  if (!converted) {
    throw std::runtime_error("Failed to convert image to 24 bit");
  }

  const unsigned w = FreeImage_GetWidth(converted);
  const unsigned h = FreeImage_GetHeight(converted);
  const unsigned data_size = w * h * 3;
  BYTE *image_data = FreeImage_GetBits(converted);

  ROS_INFO("Loading a %u x %u texture", w, h);

  //  create texture
  Ogre::TexturePtr texture;
  try {
    Ogre::DataStreamPtr data_stream;
    data_stream.bind(new Ogre::MemoryDataStream(image_data, data_size));

    const Ogre::String res_group =
        Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME;
    Ogre::TextureManager &texture_manager =
        Ogre::TextureManager::getSingleton();
    texture =
        texture_manager.loadRawData(name, res_group, data_stream, w, h,
                                    Ogre::PF_R8G8B8, Ogre::TEX_TYPE_2D, 0);
  }
  catch (...) {
    //  clean up FreeImage before re-throwing
    FreeImage_Unload(converted);
    throw;
  }

  return texture;
}
Esempio n. 4
0
	bool isThisFormat(MemChunk& mc)
	{
		FIMEMORY*         mem = FreeImage_OpenMemory((BYTE*)mc.getData(), mc.getSize());
		FREE_IMAGE_FORMAT fif = FreeImage_GetFileTypeFromMemory(mem, 0);
		FreeImage_CloseMemory(mem);
		if (fif == FIF_UNKNOWN)
			return false;
		else
			return true;
	}
Esempio n. 5
0
FIBITMAP* FreeImage_LoadFromMem(FREE_IMAGE_FORMAT fif, fiio_mem_handle *handle, int flags)
{
	if (handle && handle->data) {
		FIMEMORY *hmem = FreeImage_OpenMemory((BYTE *)handle->data, handle->datalen);
		FREE_IMAGE_FORMAT _fif = (fif != FIF_UNKNOWN) ? fif : FreeImage_GetFileTypeFromMemory(hmem, 0);
		FIBITMAP *dib = FreeImage_LoadFromMemory(_fif, hmem, flags);
		FreeImage_CloseMemory(hmem);
	}

	return NULL;
}
Esempio n. 6
0
void FI(loadImageFile)(Bitmap& bitmap, Gosu::Reader input)
{
    // Read all available input
    std::vector<BYTE> data(input.resource().size() - input.position());
    input.read(&data[0], data.size());
    FIMEMORY* fim = FreeImage_OpenMemory(&data[0], data.size());
    FREE_IMAGE_FORMAT fif = FreeImage_GetFileTypeFromMemory(fim);
    FIBITMAP* fib = FreeImage_LoadFromMemory(fif, fim, GOSU_FIFLAGS);
    checkForFreeImageErrors(fib != 0);
    fibToBitmap(bitmap, fib, fif);
}
Esempio n. 7
0
/** 
Get the embedded JPEG preview image from RAW picture with included Exif Data. 
@param RawProcessor Libraw handle
@param flags JPEG load flags
@return Returns the loaded dib if successfull, returns NULL otherwise
*/
static FIBITMAP * 
libraw_LoadEmbeddedPreview(LibRaw *RawProcessor, int flags) {
	FIBITMAP *dib = NULL;
	libraw_processed_image_t *thumb_image = NULL;
	
	try {
		// unpack data
		if(RawProcessor->unpack_thumb() != LIBRAW_SUCCESS) {
			// run silently "LibRaw : failed to run unpack_thumb"
			return NULL;
		}

		// retrieve thumb image
		int error_code = 0;
		thumb_image = RawProcessor->dcraw_make_mem_thumb(&error_code);
		if(thumb_image) {
			if(thumb_image->type != LIBRAW_IMAGE_BITMAP) {
				// attach the binary data to a memory stream
				FIMEMORY *hmem = FreeImage_OpenMemory((BYTE*)thumb_image->data, (DWORD)thumb_image->data_size);
				// get the file type
				FREE_IMAGE_FORMAT fif = FreeImage_GetFileTypeFromMemory(hmem, 0);
				if(fif == FIF_JPEG) {
					// rotate according to Exif orientation
					flags |= JPEG_EXIFROTATE;
				}
				// load an image from the memory stream
				dib = FreeImage_LoadFromMemory(fif, hmem, flags);
				// close the stream
				FreeImage_CloseMemory(hmem);
			} else if((flags & FIF_LOAD_NOPIXELS) != FIF_LOAD_NOPIXELS) {
				// convert processed data to output dib
				dib = libraw_ConvertProcessedImageToDib(thumb_image);
			}
		} else {
			throw "LibRaw : failed to run dcraw_make_mem_thumb";
		}

		// clean-up and return
		RawProcessor->dcraw_clear_mem(thumb_image);

		return dib;

	} catch(const char *text) {
		// clean-up and return
		if(thumb_image) {
			RawProcessor->dcraw_clear_mem(thumb_image);
		}
		if(text != NULL) {
			FreeImage_OutputMessageProc(s_format_id, text);
		}
	}

	return NULL;
}
Esempio n. 8
0
void TextureManager::loadTexture2DMem(unsigned char* imageData,long length) {
    FIMEMORY* hmem = FreeImage_OpenMemory(imageData,length);
    FREE_IMAGE_FORMAT fif = FreeImage_GetFileTypeFromMemory(hmem);
    FIBITMAP* image = FreeImage_LoadFromMemory(fif, hmem, 0);

    FIBITMAP* temp = image;
    image = FreeImage_ConvertTo32Bits(image);
    FreeImage_Unload(temp);
    FreeImage_CloseMemory(hmem);

    int w = FreeImage_GetWidth(image);
    int h = FreeImage_GetHeight(image);


    printf("[Texture Manager] Image loaded from memory, is %d x %d\n",w,h);

    GLubyte* textureBytes = new GLubyte[4*w*h];
    char* pixels = (char*)FreeImage_GetBits(image);

    //FreeImage loads in BGR format, so we need to swap some bytes(Or use GL_BGR)

    for(int j= 0; j<w*h; j++) {
        textureBytes[j*4+0]= pixels[j*4+2];
        textureBytes[j*4+1]= pixels[j*4+1];
        textureBytes[j*4+2]= pixels[j*4+0];
        textureBytes[j*4+3]= pixels[j*4+3];
    }


    glGenTextures(1, &(textInt));

    glBindTexture(GL_TEXTURE_2D, textInt);
    glTexImage2D(GL_TEXTURE_2D,0,GL_RGBA, w, h, 0, GL_RGBA,GL_UNSIGNED_BYTE,(GLvoid*)textureBytes );



    Textures.push_back(textInt);


    glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST );
    glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST );
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP);


    GLenum errorLoading = glGetError();
    if(errorLoading) {
        cout<<"There was an error loading the texture: "<<errorLoading<<endl;
    }


}
Esempio n. 9
0
bool FreeImageData::loadMem(unsigned char*data, unsigned long size, std::string filename)
{
    FIMEMORY * mem = FreeImage_OpenMemory(data, size);
    FREE_IMAGE_FORMAT fif = FreeImage_GetFileTypeFromMemory(mem, size);
    if (fif == FIF_UNKNOWN){
        fif = FreeImage_GetFIFFromFilename(filename.c_str());
    }
    if(fif == FIF_UNKNOWN)
        return false;
    m_bitmap = FreeImage_LoadFromMemory(fif, mem);
    FreeImage_CloseMemory(mem);
    return m_bitmap != NULL;
}
Esempio n. 10
0
FREE_IMAGE_FORMAT PngLoader::getFiFormat(const QString fileName, QByteArray & byteArray)
{
   FIMEMORY fiMemStream;
   fiMemStream.data = byteArray.data();
   FREE_IMAGE_FORMAT fiFormat = FreeImage_GetFileTypeFromMemory(&fiMemStream);

   if (fiFormat == FIF_UNKNOWN)
   {
      std::cerr << "[ERROR] Could not get file format: " << fileName.toStdString() << std::endl;
      return FIF_UNKNOWN;
   }

   return fiFormat;
}
Esempio n. 11
0
//----------------------------------------------------
bool ofImage::loadImageFromMemory(const ofBuffer & buffer, ofPixels &pix){

	int					width, height, bpp;
	bool bLoaded		= false;
	FIBITMAP * bmp		= NULL;
	FIMEMORY *hmem		= NULL;
	
	printf("loadImageFromMemory\n");

	hmem = FreeImage_OpenMemory((unsigned char*)buffer.getBuffer(), buffer.size());
	if (hmem == NULL){
		ofLog(OF_LOG_ERROR,"couldn't create memory handle! \n");
		return false;
	}

	//get the file type!
	FREE_IMAGE_FORMAT fif = FreeImage_GetFileTypeFromMemory(hmem);
	if( fif == -1 ){
		ofLog(OF_LOG_ERROR,"unable to guess format", fif);
		return false;
		FreeImage_CloseMemory(hmem);
	}


	//make the image!!
	bmp = FreeImage_LoadFromMemory(fif, hmem, 0);
	
	if( bmp != NULL ){
		bLoaded = true;
		ofLog(OF_LOG_VERBOSE,"FreeImage_LoadFromMemory worked!\n");
	}
	
	//-----------------------------

	if (bLoaded){
		putBmpIntoPixels(bmp,pix);
	} else {
		width = height = bpp = 0;
	}

	if (bmp != NULL){
		FreeImage_Unload(bmp);
	}
	
	if( hmem != NULL ){
		FreeImage_CloseMemory(hmem);
	}

	return bLoaded;
}
Esempio n. 12
0
static bool loadImage(ofPixels_<PixelType> & pix, const ofBuffer & buffer, const ofImageLoadSettings &settings){
	ofInitFreeImage();
	bool bLoaded = false;
	FIBITMAP* bmp = nullptr;
	FIMEMORY* hmem = nullptr;
	
	hmem = FreeImage_OpenMemory((unsigned char*) buffer.getData(), buffer.size());
	if (hmem == nullptr){
		ofLogError("ofImage") << "loadImage(): couldn't load image from ofBuffer, opening FreeImage memory failed";
		return false;
	}

	//get the file type!
	FREE_IMAGE_FORMAT fif = FreeImage_GetFileTypeFromMemory(hmem);
	if( fif == -1 ){
		ofLogError("ofImage") << "loadImage(): couldn't load image from ofBuffer, unable to guess image format from memory";
		FreeImage_CloseMemory(hmem);
		return false;
	}


	//make the image!!
	if(fif == FIF_JPEG) {
		int option = getJpegOptionFromImageLoadSetting(settings);
		bmp = FreeImage_LoadFromMemory(fif, hmem, option);
	} else {
		bmp = FreeImage_LoadFromMemory(fif, hmem, 0);
	}
	
	if( bmp != nullptr ){
		bLoaded = true;
	}
	
	//-----------------------------
	
	if (bLoaded){
		putBmpIntoPixels(bmp,pix);
	}

	if (bmp != nullptr){
		FreeImage_Unload(bmp);
	}
	
	if( hmem != nullptr ){
		FreeImage_CloseMemory(hmem);
	}

	return bLoaded;
}
Esempio n. 13
0
static bool loadImage(ofPixels_<PixelType> & pix, const ofBuffer & buffer){
	ofInitFreeImage();
	bool bLoaded = false;
	FIBITMAP* bmp = NULL;
	FIMEMORY* hmem = NULL;
	
	hmem = FreeImage_OpenMemory((unsigned char*) buffer.getBinaryBuffer(), buffer.size());
	if (hmem == NULL){
		ofLog(OF_LOG_ERROR, "couldn't create memory handle!");
		return false;
	}

	//get the file type!
	FREE_IMAGE_FORMAT fif = FreeImage_GetFileTypeFromMemory(hmem);
	if( fif == -1 ){
		ofLog(OF_LOG_ERROR, "unable to guess format", fif);
		return false;
		FreeImage_CloseMemory(hmem);
	}


	//make the image!!
	bmp = FreeImage_LoadFromMemory(fif, hmem, 0);
	
	if( bmp != NULL ){
		bLoaded = true;
	}
	
	//-----------------------------
	
	if (bLoaded){
		putBmpIntoPixels(bmp,pix);
	}

	if (bmp != NULL){
		FreeImage_Unload(bmp);
	}
	
	if( hmem != NULL ){
		FreeImage_CloseMemory(hmem);
	}

	return bLoaded;
}
Esempio n. 14
0
static bool loadImage(ofPixels_<PixelType> & pix, const ofBuffer & buffer){
	ofInitFreeImage();
	bool bLoaded = false;
	FIBITMAP* bmp = NULL;
	FIMEMORY* hmem = NULL;
	
	hmem = FreeImage_OpenMemory((unsigned char*) buffer.getBinaryBuffer(), buffer.size());
	if (hmem == NULL){
		ofLogError("ofImage") << "loadImage(): couldn't load image from ofBuffer, opening FreeImage memory failed";
		return false;
	}

	//get the file type!
	FREE_IMAGE_FORMAT fif = FreeImage_GetFileTypeFromMemory(hmem);
	if( fif == -1 ){
		ofLogError("ofImage") << "loadImage(): couldn't load image from ofBuffer, unable to guess image format from memory";
		return false;
		FreeImage_CloseMemory(hmem);
	}


	//make the image!!
	bmp = FreeImage_LoadFromMemory(fif, hmem, 0);
	
	if( bmp != NULL ){
		bLoaded = true;
	}
	
	//-----------------------------
	
	if (bLoaded){
		putBmpIntoPixels(bmp,pix);
	}

	if (bmp != NULL){
		FreeImage_Unload(bmp);
	}
	
	if( hmem != NULL ){
		FreeImage_CloseMemory(hmem);
	}

	return bLoaded;
}
Esempio n. 15
0
    //---------------------------------------------------------------------
    String FreeImageCodec::magicNumberToFileExt(const char *magicNumberPtr, size_t maxbytes) const
    {
        FIMEMORY* fiMem =
            FreeImage_OpenMemory((BYTE*)magicNumberPtr, static_cast<DWORD>(maxbytes));

        FREE_IMAGE_FORMAT fif = FreeImage_GetFileTypeFromMemory(fiMem, (int)maxbytes);
        FreeImage_CloseMemory(fiMem);

        if (fif != FIF_UNKNOWN)
        {
            String ext(FreeImage_GetFormatFromFIF(fif));
            StringUtil::toLowerCase(ext);
            return ext;
        }
        else
        {
            return StringUtil::BLANK;
        }
    }
Esempio n. 16
0
static INT_PTR serviceLoadFromMem(WPARAM wParam, LPARAM lParam)
{
	IMGSRVC_MEMIO *mio = (IMGSRVC_MEMIO *)wParam;
	if(mio->iLen == 0 || mio->pBuf == NULL)
		return 0;

	FIMEMORY *hmem = FreeImage_OpenMemory((BYTE *)mio->pBuf, mio->iLen);
	FREE_IMAGE_FORMAT fif = (mio->fif != FIF_UNKNOWN) ? mio->fif : mio->fif = FreeImage_GetFileTypeFromMemory(hmem, 0);
	FIBITMAP *dib = FreeImage_LoadFromMemory(fif, hmem, mio->flags);
	FreeImage_CloseMemory(hmem);

	if(dib == NULL || (lParam & IMGL_RETURNDIB))
		return (INT_PTR)dib;

	HBITMAP hbm = FreeImage_CreateHBITMAPFromDIB(dib);

	FreeImage_Unload(dib);
	return (INT_PTR)hbm;
}
Esempio n. 17
0
static FIBITMAP*
mng_LoadFromMemoryHandle(FIMEMORY *hmem, int flags = 0) {
    long offset = 0;
    FIBITMAP *dib = NULL;

    if(hmem) {
        // seek to the start of the stream
        FreeImage_SeekMemory(hmem, offset, SEEK_SET);

        // check the file signature and deduce its format
        // (the second argument is currently not used by FreeImage)
        FREE_IMAGE_FORMAT fif = FreeImage_GetFileTypeFromMemory(hmem, 0);
        if(fif != FIF_UNKNOWN) {
            dib = FreeImage_LoadFromMemory(fif, hmem, flags);
        }
    }

    return dib;
}
bool FreeImageLoader::canLoad(OS::IStream* file){
	if(m_isDummy)
		return false;
	if(file->isStream())
		return false;
	byte* data = new byte[file->length()];
	FIMEMORY* fiMem = FreeImage_OpenMemory((BYTE*)data, static_cast<DWORD>(file->length()));
	file->read(data, file->length());

	FREE_IMAGE_FORMAT fif = FreeImage_GetFileTypeFromMemory(fiMem, (int)file->length());
	FreeImage_CloseMemory(fiMem);
	delete[] data;
	//image format
//	FREE_IMAGE_FORMAT fif = FIF_UNKNOWN;
	//check the file signature and deduce its format
//	fif = FreeImage_GetFileTypeFromMemory((FIMEMORY*)data,file->length());
	if(fif == FIF_UNKNOWN)
		return false;
	return fif==m_FTType;
}
Esempio n. 19
0
void testSaveMemIO(const char *lpszPathName) {
    FIMEMORY *hmem = NULL;

    // load a regular file
    FREE_IMAGE_FORMAT fif = FreeImage_GetFileType(lpszPathName);
    FIBITMAP *dib = FreeImage_Load(fif, lpszPathName, 0);

    // open a memory handle
    hmem = FreeImage_OpenMemory();

    // save the file to memory
    FreeImage_SaveToMemory(fif, dib, hmem, 0);

    // at this point, hmem contains the entire PNG data in memory.
    // the amount of space used by the memory is equal to file_size
    long file_size = FreeImage_TellMemory(hmem);
    printf("File size : %ld\n", file_size);


    // its easy load an image from memory as well

    // seek to the start of the memory stream
    FreeImage_SeekMemory(hmem, 0L, SEEK_SET);

    // get the file type
    FREE_IMAGE_FORMAT mem_fif = FreeImage_GetFileTypeFromMemory(hmem, 0);

    // load an image from the memory handle
    FIBITMAP *check = FreeImage_LoadFromMemory(mem_fif, hmem, 0);

    // save as a regular file
    FreeImage_Save(FIF_PNG, check, "dump.png", PNG_DEFAULT);

    // make sure to free the data since FreeImage_SaveToMemory
    // will cause it to be malloc'd
    FreeImage_CloseMemory(hmem);

    FreeImage_Unload(check);
    FreeImage_Unload(dib);
}
Esempio n. 20
0
  FIBITMAP* loadWatermark()
  {

      HRSRC hRes      = ::FindResource(NULL, MAKEINTRESOURCE(PNG_Visus_Logo), "PNG");
      DWORD dwResSize = SizeofResource(NULL, hRes);
      HGLOBAL hGlobal = ::LoadResource(NULL, hRes);

      BYTE* pData = (BYTE*)LockResource(hGlobal);

      FIMEMORY* fiMem = FreeImage_OpenMemory(pData, dwResSize);
      
      FREE_IMAGE_FORMAT fif = FreeImage_GetFileTypeFromMemory(fiMem);
      FIBITMAP* fiBmp = FreeImage_LoadFromMemory(fif, fiMem);

      FreeImage_CloseMemory(fiMem);

      UnlockResource(hGlobal);   
      DeleteObject(hGlobal);   
      DeleteObject(hRes);    

      return fiBmp;
  }
Esempio n. 21
0
VALUE rb_graffik_from_memory(VALUE self, VALUE rb_data) {
  FREE_IMAGE_FORMAT fif = FIF_UNKNOWN;
  Check_Type(rb_data, T_STRING);
  
  // Get info about our in-memory image
  BYTE *data_ptr = (BYTE *) RSTRING_PTR(rb_data);
  DWORD data_length = RSTRING_LEN(rb_data);
  
  // Open up the memory stream
  FIMEMORY *stream = FreeImage_OpenMemory(data_ptr, data_length);
  
  // Make sure the stream was open
  if (stream == NULL) {
    rb_raise(rb_eTypeError, "Unable to read image from memory");
  }
  
  fif = FreeImage_GetFileTypeFromMemory(stream, 0);
  if ((fif != FIF_UNKNOWN) && FreeImage_FIFSupportsReading(fif)) {
    int flags = ((fif == FIF_JPEG) ? JPEG_ACCURATE : 0);
    // Load the image from disk
    FIBITMAP *image = FreeImage_LoadFromMemory(fif, stream, flags);
    // Release memory
    FreeImage_CloseMemory(stream);
    // Develop an instance for Ruby
    VALUE instance = Data_Wrap_Struct(self, NULL, NULL, image);
    // Store the image type as a FixNum
    rb_iv_set(instance, "@file_type", INT2FIX(fif));
    
    // If a block is given, yield to it, if not, return the instance
    if (rb_block_given_p()) {
      return rb_ensure(rb_yield, instance, rb_graffik_close, instance);
    } else {
      return instance;
    }
  }
  
  // If we couldn't load it, throw and error
  rb_raise(rb_eTypeError, "Unknown file format");
}
Esempio n. 22
0
    // 从内存中载入图片
    Bool FreeImageImage::loadFromMemory(PCVoid pData, UInt nDataSize)
    {
		unloadImage();

        FREE_IMAGE_FORMAT eImgFormat = FIF_UNKNOWN;
		FIMEMORY* pFIMemory = FreeImage_OpenMemory((UInt8*) pData, nDataSize);  
		FIBITMAP* pFIBitmap = 0;

        eImgFormat = FreeImage_GetFileTypeFromMemory(pFIMemory);
        if(eImgFormat != FIF_UNKNOWN && FreeImage_FIFSupportsReading(eImgFormat))
        {
			pFIBitmap = FreeImage_LoadFromMemory(eImgFormat, pFIMemory, 0);
        }

		Bool isSuccess = False;

		if(pFIBitmap)
		{
			// 非 32 位色图片,转换为 32 位
			UInt nBPP = FreeImage_GetBPP(pFIBitmap);
			if(nBPP != 32)
			{
				FIBITMAP* pFIBitmap32 = FreeImage_ConvertTo32Bits(pFIBitmap);
				FreeImage_Unload(pFIBitmap);
				pFIBitmap = pFIBitmap32;
			}
		}

		if(pFIBitmap)
		{
			// 加载到内存数据中
			isSuccess = _load(pFIBitmap);
			FreeImage_Unload(pFIBitmap);
		}

		FreeImage_CloseMemory(pFIMemory);
        return isSuccess;
    }
static FIBITMAP *loadImage(const std::string &file, bool convertTo32bit = true)
{
    #if  defined(__unix__) || defined(__APPLE__) || defined(_WIN32)
    FileMapper fileMap;
    if(!fileMap.open_file(file.c_str()))
        return NULL;

    FIMEMORY *imgMEM = FreeImage_OpenMemory(reinterpret_cast<unsigned char *>(fileMap.data()),
                                            (unsigned int)fileMap.size());
    FREE_IMAGE_FORMAT formato = FreeImage_GetFileTypeFromMemory(imgMEM);
    if(formato  == FIF_UNKNOWN)
        return NULL;
    FIBITMAP *img = FreeImage_LoadFromMemory(formato, imgMEM, 0);
    FreeImage_CloseMemory(imgMEM);
    fileMap.close_file();
    if(!img)
        return NULL;
    #else
    FREE_IMAGE_FORMAT formato = FreeImage_GetFileType(file.c_str(), 0);
    if(formato  == FIF_UNKNOWN)
        return NULL;
    FIBITMAP *img = FreeImage_Load(formato, file.c_str());
    if(!img)
        return NULL;
    #endif

    if(convertTo32bit)
    {
        FIBITMAP *temp;
        temp = FreeImage_ConvertTo32Bits(img);
        if(!temp)
            return NULL;
        FreeImage_Unload(img);
        img = temp;
    }
    return img;
}
Esempio n. 24
0
void testLoadMemIO(const char *lpszPathName) {
    struct stat buf;
    int result;

    // get data associated with lpszPathName
    result = stat(lpszPathName, &buf);
    if(result == 0) {
        // allocate a memory buffer and load temporary data
        BYTE *mem_buffer = (BYTE*)malloc(buf.st_size * sizeof(BYTE));
        if(mem_buffer) {
            FILE *stream = fopen(lpszPathName, "rb");
            if(stream) {
                fread(mem_buffer, sizeof(BYTE), buf.st_size, stream);
                fclose(stream);

                // attach the binary data to a memory stream
                FIMEMORY *hmem = FreeImage_OpenMemory(mem_buffer, buf.st_size);

                // get the file type
                FREE_IMAGE_FORMAT fif = FreeImage_GetFileTypeFromMemory(hmem, 0);

                // load an image from the memory stream
                FIBITMAP *check = FreeImage_LoadFromMemory(fif, hmem, PNG_DEFAULT);

                // save as a regular file
                FreeImage_Save(FIF_PNG, check, "blob.png", PNG_DEFAULT);
                FreeImage_Unload(check);

                // close the stream
                FreeImage_CloseMemory(hmem);

            }
        }
        // user is responsible for freeing the data
        free(mem_buffer);
    }
}
Esempio n. 25
0
//------------------------------------------------------------------
void ofxAdvancedImage::loadFromData(unsigned char * datasource, int len) {
	//Load image from memory code, based on Zach's code updated by madparker on OF Forum
	//if we already have a loaded image clear it
	// if(isValid()){
    clear();     
	// }
	
	//create a freeimage memory handle from the buffer address
	FIMEMORY *hmem = NULL;
	hmem = FreeImage_OpenMemory((BYTE *)datasource,len);
	if (hmem == NULL){ printf("couldn't create memory handle! \n"); return; }
	
	//get the file type!
	FREE_IMAGE_FORMAT fif = FreeImage_GetFileTypeFromMemory(hmem);
	
	//make the image!!
	putBmpIntoPixels(FreeImage_LoadFromMemory(fif, hmem, 0), myPixels);
	//  bmp = FreeImage_LoadFromMemory(fif, hmem, 0);
	
	//free our memory
	FreeImage_CloseMemory(hmem);
	
	if (getBmpFromPixels(myPixels) == NULL){ printf("couldn't create bmp! \n"); return; }
	
	//flip it!
	FreeImage_FlipVertical(getBmpFromPixels(myPixels));
	
	if (myPixels.bAllocated == true && bUseTexture == true){
		tex.allocate(myPixels.width, myPixels.height, myPixels.glDataType);
	}   
	
	swapRgb(myPixels);
	
	update();
	
	reset();
}
Esempio n. 26
0
	FIBITMAP* getFIInfo(MemChunk& data, SImage::info_t& info)
	{
		// Get FreeImage bitmap info from entry data
		FIMEMORY*         mem = FreeImage_OpenMemory((BYTE*)data.getData(), data.getSize());
		FREE_IMAGE_FORMAT fif = FreeImage_GetFileTypeFromMemory(mem, 0);
		FIBITMAP*         bm  = FreeImage_LoadFromMemory(fif, mem, 0);
		FreeImage_CloseMemory(mem);

		// Check it created/read ok
		if (!bm)
			return nullptr;

		// Get info from image
		info.width     = FreeImage_GetWidth(bm);
		info.height    = FreeImage_GetHeight(bm);
		info.colformat = RGBA; // Generic images always converted to RGBA on loading
		info.format    = id_;

		// Check if palette supplied
		if (FreeImage_GetColorsUsed(bm) > 0)
			info.has_palette = true;

		return bm;
	}
Esempio n. 27
0
	GLuint OGLRenderSystem::GetTextureCache( TextureBase* tex )
	{
		GLuint& cache = (GLuint&)tex->mCache;
		if( tex->IsDirty( ) )
		{
			if( cache ) {
				glDeleteTextures( 1, &cache );
				cache = 0;
			}

			int texformat = tex->GetFormat( );
			if( texformat == 0 ) {
				glGenTextures( 1, &cache );
				if( !cache )
				{
					printf( "Failed to generate texture :: cache = 0\n" );
					return 0;
				}

				glBindTexture( GL_TEXTURE_2D, cache );
				glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR );
				glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR );

				DWORD dwFlags = *(DWORD*)(tex->mData + 0x50);
				if( dwFlags & 0x40 )
				{
					DWORD bpp = *(DWORD*)(tex->mData + 0x58);
					int hasAlpha = dwFlags & 0x1;
					DWORD aMask = *(DWORD*)(tex->mData + 0x68);

					int type;
					int format;
					int data;

					if( bpp == 16 ) {
						if( aMask == 0x80 ) {
							//a1r5g5b5
							format = GL_RGB5_A1;
							type = GL_BGRA;
							data = GL_UNSIGNED_SHORT_1_5_5_5_REV;
						} else {
							//a4r4g4b4
							if( hasAlpha ) {
								format = GL_RGBA4;
								type = GL_BGRA;
								data = GL_UNSIGNED_SHORT_4_4_4_4_REV;
							} else {
								format = GL_RGB4;
								type = GL_BGR;
								data = GL_UNSIGNED_SHORT_4_4_4_4_REV;
							}
						}
					} else if( bpp == 32 ) {
						if( hasAlpha ) {
							format = GL_RGBA;
							type = GL_BGRA;
							data = GL_UNSIGNED_INT_8_8_8_8_REV;
						} else {
							format = GL_RGB;
							type = GL_BGR;
							data = GL_UNSIGNED_INT_8_8_8_8_REV;
						}
					}

					DWORD width = tex->GetWidth( );
					DWORD height = tex->GetHeight( );

					glTexImage2D( GL_TEXTURE_2D, 0, format, width, height, 0, type, data, (GLvoid*)(tex->mData + 0x80) );
				} else {
					FIMEMORY* imgmem = FreeImage_OpenMemory( tex->mData, tex->mDataLen );
					FREE_IMAGE_FORMAT fif = FreeImage_GetFileTypeFromMemory( imgmem );
					FIBITMAP* img = FreeImage_LoadFromMemory( fif, imgmem, 0 );

					FIBITMAP* temp = img;
					img = FreeImage_ConvertTo32Bits( img );
					FreeImage_FlipVertical( img );

					glTexImage2D( GL_TEXTURE_2D, 0, 4, FreeImage_GetWidth( img ), FreeImage_GetHeight( img ), 0, GL_BGRA, GL_UNSIGNED_BYTE, (GLvoid*)FreeImage_GetBits( img ) );

					FreeImage_Unload( temp );
					FreeImage_Unload( img );
					FreeImage_CloseMemory( imgmem );
				}
			} else if( texformat == TextureFormat::A8 ) {
				glGenTextures( 1, &cache );
				glBindTexture( GL_TEXTURE_2D, cache );
				glTexImage2D( GL_TEXTURE_2D, 0, GL_ALPHA8, tex->GetWidth( ), tex->GetHeight( ), 0, GL_ALPHA, GL_UNSIGNED_BYTE, (GLvoid*)tex->mData );
			} else {
				printf( "Failed to create Texture Cache :: Invalid format: %d\n", texformat );
				return 0;
			}

			tex->SetDirty( false );
		}
		return cache;
	};
Esempio n. 28
0
FIBITMAP *GraphicsHelps::loadImage(std::string file, bool convertTo32bit)
{
#ifdef DEBUG_BUILD
    ElapsedTimer loadingTime;
    ElapsedTimer fReadTime;
    ElapsedTimer imgConvTime;
    loadingTime.start();
    fReadTime.start();
#endif
#if  defined(__unix__) || defined(__APPLE__) || defined(_WIN32)
    FileMapper fileMap;

    if(!fileMap.open_file(file.c_str()))
        return NULL;

    FIMEMORY *imgMEM = FreeImage_OpenMemory(reinterpret_cast<unsigned char *>(fileMap.data()),
                                            static_cast<unsigned int>(fileMap.size()));
    FREE_IMAGE_FORMAT formato = FreeImage_GetFileTypeFromMemory(imgMEM);

    if(formato  == FIF_UNKNOWN)
        return NULL;

    FIBITMAP *img = FreeImage_LoadFromMemory(formato, imgMEM, 0);
    FreeImage_CloseMemory(imgMEM);
    fileMap.close_file();

    if(!img)
        return NULL;

#else
    FREE_IMAGE_FORMAT formato = FreeImage_GetFileType(file.toUtf8().data(), 0);

    if(formato  == FIF_UNKNOWN)
        return NULL;

    FIBITMAP *img = FreeImage_Load(formato, file.toUtf8().data());

    if(!img)
        return NULL;

#endif
#ifdef DEBUG_BUILD
    long long fReadTimeElapsed = static_cast<long long>(fReadTime.elapsed());
    long long imgConvertElapsed = 0;
#endif

    if(convertTo32bit)
    {
#ifdef DEBUG_BUILD
        imgConvTime.start();
#endif
        FIBITMAP *temp;
        temp = FreeImage_ConvertTo32Bits(img);

        if(!temp)
            return NULL;

        FreeImage_Unload(img);
        img = temp;
#ifdef DEBUG_BUILD
        imgConvertElapsed = static_cast<long long>(imgConvTime.elapsed());
#endif
    }

#ifdef DEBUG_BUILD
    D_pLogDebug("File read of texture %s passed in %d milliseconds", file.c_str(), static_cast<int>(fReadTimeElapsed));
    D_pLogDebug("Conv to 32-bit of %s passed in %d milliseconds", file.c_str(), static_cast<int>(imgConvertElapsed));
    D_pLogDebug("Total Loading of image %s passed in %d milliseconds", file.c_str(), static_cast<int>(loadingTime.elapsed()));
#endif
    return img;
}
Esempio n. 29
0
File: loader.c Progetto: eXeC64/imv
static void *bg_new_img(void *data)
{
  /* so we can poll for it */
  block_usr1_signal();

  struct imv_loader *ldr = data;
  char path[PATH_MAX] = "-";

  pthread_mutex_lock(&ldr->lock);
  int from_stdin = !strncmp(path, ldr->path, 2);
  if(!from_stdin) {
    (void)snprintf(path, PATH_MAX, "%s", ldr->path);
  }
  pthread_mutex_unlock(&ldr->lock);

  FREE_IMAGE_FORMAT fmt;
  if (from_stdin) {
    pthread_mutex_lock(&ldr->lock);
    ldr->fi_buffer = FreeImage_OpenMemory(ldr->buffer, ldr->buffer_size);
    fmt = FreeImage_GetFileTypeFromMemory(ldr->fi_buffer, 0);
    pthread_mutex_unlock(&ldr->lock);
  } else {
    fmt = FreeImage_GetFileType(path, 0);
  }
  if(fmt == FIF_UNKNOWN) {
    if (from_stdin) {
      pthread_mutex_lock(&ldr->lock);
      FreeImage_CloseMemory(ldr->fi_buffer);
      pthread_mutex_unlock(&ldr->lock);
    }
    error_occurred(ldr);
    return NULL;
  }

  int num_frames = 1;
  FIMULTIBITMAP *mbmp = NULL;
  FIBITMAP *bmp = NULL;
  int width, height;
  int raw_frame_time = 100; /* default to 100 */

  if(fmt == FIF_GIF) {
    if(from_stdin) {
      pthread_mutex_lock(&ldr->lock);
      mbmp = FreeImage_LoadMultiBitmapFromMemory(FIF_GIF, ldr->fi_buffer,
          GIF_LOAD256);
      pthread_mutex_unlock(&ldr->lock);
    } else {
      mbmp = FreeImage_OpenMultiBitmap(FIF_GIF, path,
      /* don't create file */ 0,
      /* read only */ 1,
      /* keep in memory */ 1,
      /* flags */ GIF_LOAD256);
    }
    if(!mbmp) {
      error_occurred(ldr);
      return NULL;
    }

    num_frames = FreeImage_GetPageCount(mbmp);

    FIBITMAP *frame = FreeImage_LockPage(mbmp, 0);
    width = FreeImage_GetWidth(frame);
    height = FreeImage_GetHeight(frame);
    bmp = FreeImage_ConvertTo32Bits(frame);

    /* get duration of first frame */
    FITAG *tag = NULL;
    FreeImage_GetMetadata(FIMD_ANIMATION, frame, "FrameTime", &tag);
    if(FreeImage_GetTagValue(tag)) {
      raw_frame_time = *(int*)FreeImage_GetTagValue(tag);
    }
    FreeImage_UnlockPage(mbmp, frame, 0);

  } else {
    /* Future TODO: If we load image line-by-line we could stop loading large
     * ones before wasting much more time/memory on them. */

    int flags = (fmt == FIF_JPEG) ? JPEG_EXIFROTATE : 0;
    FIBITMAP *image;
    if(from_stdin) {
      pthread_mutex_lock(&ldr->lock);
      image = FreeImage_LoadFromMemory(fmt, ldr->fi_buffer, flags);
      pthread_mutex_unlock(&ldr->lock);
    } else {
      image = FreeImage_Load(fmt, path, flags);
    }
    if(!image) {
      error_occurred(ldr);
      pthread_mutex_lock(&ldr->lock);
      FreeImage_CloseMemory(ldr->fi_buffer);
      ldr->fi_buffer = NULL;
      pthread_mutex_unlock(&ldr->lock);
      return NULL;
    }

    /* Check for cancellation before we convert pixel format */
    if(is_thread_cancelled()) {
      FreeImage_Unload(image);
      return NULL;
    }

    width = FreeImage_GetWidth(bmp);
    height = FreeImage_GetHeight(bmp);
    bmp = FreeImage_ConvertTo32Bits(image);
    FreeImage_Unload(image);
  }

  /* now update the loader */
  pthread_mutex_lock(&ldr->lock);

  /* check for cancellation before finishing */
  if(is_thread_cancelled()) {
    if(mbmp) {
      FreeImage_CloseMultiBitmap(mbmp, 0);
    }
    if(bmp) {
      FreeImage_Unload(bmp);
    }
    pthread_mutex_unlock(&ldr->lock);
    return NULL;
  }

  if(ldr->mbmp) {
    FreeImage_CloseMultiBitmap(ldr->mbmp, 0);
  }

  if(ldr->bmp) {
    FreeImage_Unload(ldr->bmp);
  }

  ldr->mbmp = mbmp;
  ldr->bmp = bmp;
  if(ldr->out_bmp) {
    FreeImage_Unload(ldr->out_bmp);
  }
  ldr->out_bmp = FreeImage_Clone(bmp);
  ldr->out_is_new_image = 1;
  ldr->width = width;
  ldr->height = height;
  ldr->cur_frame = 0;
  ldr->next_frame = 1;
  ldr->num_frames = num_frames;
  ldr->frame_time = (double)raw_frame_time * 0.0001;

  pthread_mutex_unlock(&ldr->lock);
  return NULL;
}
Esempio n. 30
0
Texture* FreeImageImageCodec::load(const RawDataContainer& data, Texture* result)
{
    int len = (int)data.getSize();
    FIMEMORY *mem = 0;
    FIBITMAP *img = 0;
    Texture *retval = 0;

    try
    {
        mem = FreeImage_OpenMemory(static_cast<BYTE*>(const_cast<std::uint8_t*>(data.getDataPtr())), len);
        if (mem == 0)
            throw MemoryException("Unable to open memory stream, FreeImage_OpenMemory failed");

        FREE_IMAGE_FORMAT fif = FreeImage_GetFileTypeFromMemory(mem, len);

        if (fif == FIF_UNKNOWN) // it may be that it's TARGA or MNG
        {
            fif = FIF_TARGA;
            img = FreeImage_LoadFromMemory(fif, mem, 0);

            if (img == 0)
            {
                fif = FIF_MNG;
                img = FreeImage_LoadFromMemory(fif, mem, 0);
            }
        }
        else
            img = FreeImage_LoadFromMemory(fif, mem, 0);

        if (img == 0)
            throw GenericException("Unable to load image, FreeImage_LoadFromMemory failed");

        FIBITMAP *newImg = FreeImage_ConvertTo32Bits(img);
        if (newImg == 0)
            throw GenericException("Unable to convert image, FreeImage_ConvertTo32Bits failed");
        FreeImage_Unload(img);
        img = newImg;
        newImg = 0;

        // FreeImage pixel format for little-endian architecture (which CEGUI
        // supports) is like BGRA. We need to convert that to RGBA.
        //
        // It is now:
        // RED_MASK		0x00FF0000
        // GREEN_MASK	0x0000FF00
        // BLUE_MASK	0x000000FF
        // ALPHA_MASK	0xFF000000
        //
        // It should be:
        // RED_MASK		0x000000FF
        // GREEN_MASK	0x0000FF00
        // BLUE_MASK	0x00FF0000
        // ALPHA_MASK	0xFF000000

        unsigned int pitch = FreeImage_GetPitch(img);
        unsigned int height = FreeImage_GetHeight(img);
        unsigned int width = FreeImage_GetWidth(img);
        std::uint8_t *rawBuf = new std::uint8_t[width * height << 2];

        // convert the bitmap to raw bits (top-left pixel first)
        FreeImage_ConvertToRawBits(rawBuf, img, pitch, 32,
                                   FI_RGBA_RED_MASK, FI_RGBA_GREEN_MASK, FI_RGBA_BLUE_MASK, true);

        // We need to convert pixel format a little
        // NB: little endian only - I think(!)
#if FREEIMAGE_COLORORDER == FREEIMAGE_COLORORDER_BGR
        for (unsigned int i = 0; i < height; ++i)
        {
            for (unsigned int j = 0; j < width; ++j)
            {
                unsigned int p = *(((unsigned int*)(rawBuf + i * pitch)) + j);
                unsigned int r = (p >> 16) & 0x000000FF;
                unsigned int b = (p << 16) & 0x00FF0000;
                p &= 0xFF00FF00;
                p |= r | b;
                // write the adjusted pixel back
                *(((unsigned int*)(rawBuf + i * pitch)) + j) = p;
            }
        }
#endif
        FreeImage_Unload(img);
        img = 0;

        result->loadFromMemory(rawBuf, Sizef(width, height), Texture::PF_RGBA);
        delete [] rawBuf;
        retval = result;
    }
    catch (Exception&)
    {
    }

    if (img != 0) FreeImage_Unload(img);
    if (mem != 0) FreeImage_CloseMemory(mem);

    return retval;
}