示例#1
0
//----------------------------------------------------------------
void  ofImage::saveImageFromPixels(string fileName, ofPixels &pix){

	if (pix.isAllocated() == false){
		ofLog(OF_LOG_ERROR,"error saving image - pixels aren't allocated");
		return;
	}

	#ifdef TARGET_LITTLE_ENDIAN
		pix.swapRgb();
	#endif

	FIBITMAP * bmp	= getBmpFromPixels(pix);

	#ifdef TARGET_LITTLE_ENDIAN
		pix.swapRgb();
	#endif

	fileName = ofToDataPath(fileName);
	if (pix.isAllocated()){
		FREE_IMAGE_FORMAT fif = FIF_UNKNOWN;
		fif = FreeImage_GetFileType(fileName.c_str(), 0);
		if(fif == FIF_UNKNOWN) {
			// or guess via filename
			fif = FreeImage_GetFIFFromFilename(fileName.c_str());
		}
		if((fif != FIF_UNKNOWN) && FreeImage_FIFSupportsReading(fif)) {
			if((FREE_IMAGE_FORMAT)fif != FIF_JPEG)
			   FreeImage_Save(fif, bmp, fileName.c_str());
			else
			   FreeImage_Save(fif, bmp, fileName.c_str(),JPEG_QUALITYSUPERB);
		}
	}

	if (bmp != NULL){
		FreeImage_Unload(bmp);
	}
}
示例#2
0
//----------------------------------------------------------------
// copied directly from core ofImage::saveImageFromPixels, with added bool return value
bool ofxImage::saveImageFromPixels(string fileName, ofPixels &pix){
	bool result = false;
	if (pix.bAllocated == false){
		ofLog(OF_LOG_ERROR,"error saving image - pixels aren't allocated");
		return result;
	}
	
	/*
#ifdef TARGET_LITTLE_ENDIAN
	if (pix.bytesPerPixel != 1) swapRgb(pix);
#endif
	*/
	FIBITMAP * bmp	= getBmpFromPixels(pix);
	/*
#ifdef TARGET_LITTLE_ENDIAN
	if (pix.bytesPerPixel != 1) swapRgb(pix);
#endif
	 */
	 
	fileName = ofToDataPath(fileName);
	if (pix.bAllocated == true){
		FREE_IMAGE_FORMAT fif = FIF_UNKNOWN;
		fif = FreeImage_GetFileType(fileName.c_str(), 0);
		if(fif == FIF_UNKNOWN) {
			// or guess via filename
			fif = FreeImage_GetFIFFromFilename(fileName.c_str());
		}
		if((fif != FIF_UNKNOWN) && FreeImage_FIFSupportsReading(fif)) {
			result = FreeImage_Save(fif, bmp, fileName.c_str(), 0);
		}
	}
	
	if (bmp != NULL){
		FreeImage_Unload(bmp);
	}
	return result;
}
bool CTexture::LoadTexture2D(string a_sPath, bool bGenerateMipMaps)
{
	FREE_IMAGE_FORMAT fif = FIF_UNKNOWN;
	FIBITMAP* dib(0);

	fif = FreeImage_GetFileType(a_sPath.c_str(), 0); // Check the file signature and deduce its format

	if(fif == FIF_UNKNOWN) // If still unknown, try to guess the file format from the file extension
		fif = FreeImage_GetFIFFromFilename(a_sPath.c_str());
	
	if(fif == FIF_UNKNOWN) // If still unknown, return failure
		return false;

	if(FreeImage_FIFSupportsReading(fif)) // Check if the plugin has reading capabilities and load the file
		dib = FreeImage_Load(fif, a_sPath.c_str());
	if(!dib)
		return false;

	BYTE* bDataPointer = FreeImage_GetBits(dib); // Retrieve the image data

	// If somehow one of these failed (they shouldn't), return failure
	if(bDataPointer == NULL || FreeImage_GetWidth(dib) == 0 || FreeImage_GetHeight(dib) == 0)
		return false;

	GLenum format;
	int bada = FreeImage_GetBPP(dib);
	if(FreeImage_GetBPP(dib) == 32)format = GL_RGBA;
	if(FreeImage_GetBPP(dib) == 24)format = GL_BGR;
	if(FreeImage_GetBPP(dib) == 8)format = GL_LUMINANCE;
	CreateFromData(bDataPointer, FreeImage_GetWidth(dib), FreeImage_GetHeight(dib), FreeImage_GetBPP(dib), format, bGenerateMipMaps);
	
	FreeImage_Unload(dib);

	sPath = a_sPath;

	return true; // Success
}
示例#4
0
uint8_t picture_load(const char* filename) {
  FREE_IMAGE_FORMAT fif = FIF_UNKNOWN;
  int flag = 0;
  FIBITMAP *temp;
  fif=FreeImage_GetFileType(filename, 0);
  if(fif == FIF_UNKNOWN) {
    fif=FreeImage_GetFIFFromFilename(filename);
  }
  if((fif != FIF_UNKNOWN) && FreeImage_FIFSupportsReading(fif)) {
    temp = FreeImage_Load(fif, filename,flag);
    if(temp) {
      dib = FreeImage_ConvertTo24Bits(temp);
      FreeImage_Unload(temp);
      if(dib) {
        w = FreeImage_GetWidth(dib);
        h = FreeImage_GetHeight(dib);
        if(w == 0 || h == 0) {
          FreeImage_Unload(dib);
          dib=NULL;
          return (last_error = PIC_LOADING);
        } else if(w > 1000 || h > 4000) {
          FreeImage_Unload(dib);
          dib=NULL;
          return (last_error = PIC_SIZE);
        } else {
          return (last_error = analyze());
        }
      } else {
        return (last_error = PIC_CONVERT);
      }
    } else {
      return (last_error = PIC_LOADING);
    }
  } else {
    return (last_error = PIC_FORMAT);
  }
}
/** Generic image loader
@param lpszPathName Pointer to the full file name
@param flag Optional load flag constant
@return Returns the loaded dib if successful, returns NULL otherwise
*/
bitmap_ptr GenericLoader(const std::string& lpszPathName, int flag = 0) {
	auto fif = FIF_UNKNOWN;

	// check if file path is not empty
	if (lpszPathName.empty())
		return nullptr;

	// check the file signature and deduce its format
	// (the second argument is currently not used by FreeImage)
	fif = FreeImage_GetFileType(lpszPathName.c_str(), 0);
	if (fif == FIF_UNKNOWN) {
		// no signature ?
		// try to guess the file format from the file extension
		fif = FreeImage_GetFIFFromFilename(lpszPathName.c_str());
	}
	// check that the plugin has reading capabilities ...
	if ((fif != FIF_UNKNOWN) && FreeImage_FIFSupportsReading(fif)) {
		// ok, let's load the file
		bitmap_ptr dib(FreeImage_Load(fif, lpszPathName.c_str(), flag));
		// unless a bad file format, we are done !
		return dib;
	}
	return nullptr;
}
bool NFreeImage::Load(const std::string &i_rFilename)
{
    Unload();

    FREE_IMAGE_FORMAT FreeImageFormat = FreeImage_GetFileType(i_rFilename.c_str(), 0);

    if(FreeImageFormat == FIF_UNKNOWN)
    {
        FreeImageFormat = FreeImage_GetFIFFromFilename(i_rFilename.c_str());

    }

    if(FreeImageFormat == FIF_UNKNOWN)
    {
        return false;
    }

    if(FreeImage_FIFSupportsReading(FreeImageFormat));
    {
        m_pImage = FreeImage_Load(FreeImageFormat, i_rFilename.c_str());
    }

    return m_pImage != 0;
}
示例#7
0
//----------------------------------------------------
bool ofImage::loadImageIntoPixels(string fileName, ofPixels &pix){

	int					width, height, bpp;
	ofImageType			type;
	fileName			= ofToDataPath(fileName);
	bool bLoaded		= false;
	FIBITMAP 			* bmp = NULL;


	FREE_IMAGE_FORMAT fif = FIF_UNKNOWN;
	fif = FreeImage_GetFileType(fileName.c_str(), 0);
	if(fif == FIF_UNKNOWN) {
		// or guess via filename
		fif = FreeImage_GetFIFFromFilename(fileName.c_str());
	}
	if((fif != FIF_UNKNOWN) && FreeImage_FIFSupportsReading(fif)) {
		bmp					= FreeImage_Load(fif, fileName.c_str(), 0);

		if (bmp){
			bLoaded = true;
		}
	}
	//-----------------------------

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

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

	return bLoaded;
}
BYTE *FileManager::loadImage(const char *name, size_t *width, size_t *height) const {
	FREE_IMAGE_FORMAT imageFormat = FIF_UNKNOWN;
	FIBITMAP *dib = nullptr;

	imageFormat = FreeImage_GetFileType(name, 0);
	
	if (imageFormat == FIF_UNKNOWN)
		imageFormat = FreeImage_GetFIFFromFilename(name);

	if (imageFormat == FIF_UNKNOWN)
		return nullptr;

	if (FreeImage_FIFSupportsReading(imageFormat))
		dib = FreeImage_Load(imageFormat, name);

	if (!dib)
		return nullptr;

	BYTE *result = FreeImage_GetBits(dib);
	*width = FreeImage_GetWidth(dib);
	*height = FreeImage_GetHeight(dib);

	return result;
}
示例#9
0
bool Texture::Load()
{
    FREE_IMAGE_FORMAT fif = FIF_UNKNOWN;

    fif = FreeImage_GetFileType(Path.c_str(), 0);
    if(fif == FIF_UNKNOWN)
          fif = FreeImage_GetFIFFromFilename(Path.c_str());

    if(fif == FIF_UNKNOWN)
        return false;

    if(FreeImage_FIFSupportsReading(fif))
    {
        FIBITMAP* dib = FreeImage_Load(fif, Path.c_str());
        FIBITMAP* dib32 = FreeImage_ConvertTo32Bits(dib);
        if(dib32)
        {
            uint8_t* TextureBits = FreeImage_GetBits(dib32);
            unsigned int TextureWidth = FreeImage_GetWidth(dib);
            unsigned int TextureHeight = FreeImage_GetHeight(dib);
            if(TextureBits && TextureWidth && TextureHeight)
            {
                glGenTextures(1, &ID);
                glActiveTexture(GL_TEXTURE0);
                glBindTexture(GL_TEXTURE_2D, ID);
            		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
                    glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, TextureWidth, TextureHeight, 0, GL_BGRA, GL_UNSIGNED_BYTE, TextureBits);
                glBindTexture(GL_TEXTURE_2D, 0);
            }

        }
        FreeImage_Unload(dib);
        return true;
    }
    return false;
}
static bool loadImage(ofPixels_<PixelType> & pix, string fileName){
	ofInitFreeImage();
	if(fileName.substr(0, 7) == "http://") {
		return ofLoadImage(pix, ofLoadURL(fileName).data);
	}
	
	fileName = ofToDataPath(fileName);
	bool bLoaded = false;
	FIBITMAP * bmp = NULL;

	FREE_IMAGE_FORMAT fif = FIF_UNKNOWN;
	fif = FreeImage_GetFileType(fileName.c_str(), 0);
	if(fif == FIF_UNKNOWN) {
		// or guess via filename
		fif = FreeImage_GetFIFFromFilename(fileName.c_str());
	}
	if((fif != FIF_UNKNOWN) && FreeImage_FIFSupportsReading(fif)) {
		bmp = FreeImage_Load(fif, fileName.c_str(), 0);

		if (bmp != NULL){
			bLoaded = true;
		}
	}
	
	//-----------------------------

	if ( bLoaded ){
		putBmpIntoPixels(bmp,pix);
	}

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

	return bLoaded;
}
示例#11
0
void pre_lzw_mp::do_lzw(QString n){
    QString job = n;
    QString images_src = src + "\\" +n;
    QString write_dst = dst + "\\" + n;
    QString image_name, saved_name;
    int dot_pos;
    QString image_path;
    QDir images_dir(images_src);
    QDir write_dir(dst);
    write_dir.mkdir(job);
    qDebug()<<images_src;
    qDebug()<<write_dst;
    QFileInfoList images_info_list = images_dir.entryInfoList();
    QList<QFileInfo>::iterator image_iter = images_info_list.begin();
    FreeImage_Initialise(true);
    for(; image_iter < images_info_list.end(); ++image_iter){
        if((*image_iter).isDir()){
//            qDebug()<<(*image_iter).fileName();
            continue;
        }
        image_name = (*image_iter).fileName();
        dot_pos = image_name.indexOf(".");
        saved_name = write_dst + "\\" + image_name.left(dot_pos) + "_c.tif";
        image_path = (*image_iter).absoluteFilePath();
        FREE_IMAGE_FORMAT fif = FreeImage_GetFileType(image_path.toStdString().c_str(), 0);
        if(fif == FIF_UNKNOWN){
            fif = FreeImage_GetFIFFromFilename(image_path.toStdString().c_str());
        }
        if((fif != FIF_UNKNOWN) && FreeImage_FIFSupportsReading(fif)){
            FIBITMAP *image = FreeImage_Load(fif, image_path.toStdString().c_str());
            FreeImage_Save(FIF_TIFF, image, saved_name.toStdString().c_str(), TIFF_LZW);
            FreeImage_Unload(image);
        }        
    }
    FreeImage_DeInitialise();
}
示例#12
0
static void saveImage(const ofPixels_<PixelType> & _pix, const std::string& _fileName, ofImageQualityType qualityLevel) {
	// Make a local copy.
	ofPixels_<PixelType> pix = _pix;

	ofInitFreeImage();
	if (pix.isAllocated() == false){
		ofLogError("ofImage") << "saveImage(): couldn't save \"" << _fileName << "\", pixels are not allocated";
		return;
	}

	#ifdef TARGET_LITTLE_ENDIAN
	if(sizeof(PixelType) == 1 && (pix.getPixelFormat()==OF_PIXELS_RGB || pix.getPixelFormat()==OF_PIXELS_RGBA)) {
		pix.swapRgb();
	}
	#endif

	FIBITMAP * bmp	= getBmpFromPixels(pix);

	#ifdef TARGET_LITTLE_ENDIAN
	if(sizeof(PixelType) == 1 && (pix.getPixelFormat()==OF_PIXELS_BGR || pix.getPixelFormat()==OF_PIXELS_BGRA)) {
		pix.swapRgb();
	}
	#endif
	
	ofFilePath::createEnclosingDirectory(_fileName);
	std::string fileName = ofToDataPath(_fileName);
	FREE_IMAGE_FORMAT fif = FIF_UNKNOWN;
	fif = FreeImage_GetFileType(fileName.c_str(), 0);
	if(fif == FIF_UNKNOWN) {
		// or guess via filename
		fif = FreeImage_GetFIFFromFilename(fileName.c_str());
	}
	if((fif != FIF_UNKNOWN) && FreeImage_FIFSupportsReading(fif)) {
		if(fif == FIF_JPEG) {
			int quality = JPEG_QUALITYSUPERB;
			switch(qualityLevel) {
				case OF_IMAGE_QUALITY_WORST: quality = JPEG_QUALITYBAD; break;
				case OF_IMAGE_QUALITY_LOW: quality = JPEG_QUALITYAVERAGE; break;
				case OF_IMAGE_QUALITY_MEDIUM: quality = JPEG_QUALITYNORMAL; break;
				case OF_IMAGE_QUALITY_HIGH: quality = JPEG_QUALITYGOOD; break;
				case OF_IMAGE_QUALITY_BEST: quality = JPEG_QUALITYSUPERB; break;
			}
			FreeImage_Save(fif, bmp, fileName.c_str(), quality);
		} else {
			if(qualityLevel != OF_IMAGE_QUALITY_BEST) {
				ofLogWarning("ofImage") << "saveImage(): ofImageCompressionType only applies to JPEGs,"
					<< " ignoring value for \" "<< fileName << "\"";
			}
			
			if (fif == FIF_GIF) {
				FIBITMAP* convertedBmp;
				if(pix.getImageType() == OF_IMAGE_COLOR_ALPHA) {
					// this just converts the image to grayscale so it can save something
					convertedBmp = FreeImage_ConvertTo8Bits(bmp);
				} else {
					// this will create a 256-color palette from the image
					convertedBmp = FreeImage_ColorQuantize(bmp, FIQ_NNQUANT);
				}
				FreeImage_Save(fif, convertedBmp, fileName.c_str());
				if (convertedBmp != nullptr){
					FreeImage_Unload(convertedBmp);
				}
			} else {
				FreeImage_Save(fif, bmp, fileName.c_str());
			}
		}
	}

	if (bmp != nullptr){
		FreeImage_Unload(bmp);
	}
}
示例#13
0
MOboolean moTextureBuffer::UpdateImages( MOint maxfiles ) {

	//carga los frames desde los archivos
	moFile* pFile;

	MOint counter = 0;

	if (!m_pDirectory) return false;

	if (m_ActualImage>=(MOint)m_pDirectory->GetFiles().Count()) {
		m_bLoadCompleted = true;
		return true;
	}

	if (m_ActualImage==0)
		pFile = m_pDirectory->FindFirst();
	else
		pFile = m_pDirectory->Find(m_ActualImage);

	if (pFile)
	do {
		if ( pFile->GetType()==MO_FILETYPE_LOCAL && pFile->Exists()) {

			//LOAD AND UNCOMPRESS IMAGE
			FREE_IMAGE_FORMAT fif;
			fif = FreeImage_GetFileType( pFile->GetCompletePath(), 0);

			if( fif == FIF_UNKNOWN ) {
				// try to guess the file format from the file extension
				fif = FreeImage_GetFIFFromFilename(pFile->GetCompletePath());
			}

			if( (fif != FIF_UNKNOWN) && FreeImage_FIFSupportsReading(fif) ) {
				//decodificamos el archivo
				FIBITMAP* pImage;
				pImage = FreeImage_Load( fif, pFile->GetCompletePath(), 0);

				//ONCE LOADED SAVE ON EVERY VIDEOBUFFER
				if (pImage) {

					//for(MOuint b = 0; b<m_VideoBuffers.Count(); b++) {

						//moVideoBuffer* pVideoBuffer = m_VideoBuffers[b];

						//if (pVideoBuffer)
                    //LoadImage(  , pImage, m_ActualImage );
                    MODebug2->Push( moText("moTextureBuffer::UpdateImages > Trying to load image:") +  (moText)pFile->GetCompletePath() );
                    if ( LoadImage( m_FolderName + moSlash + pFile->GetFileName() , pImage, m_ActualImage ) ) {
                        m_ImagesProcessed++;
                        if ( m_ActualImage == (m_pDirectory->GetFiles().Count()-2) ) {
                            MODebug2->Log( moText(" ####TEXTUREBUFFER LEVEL HISTOGRAM####"));
                            moText barra;
                            moText nivel;
                            barra = moText("###################################################################################");

                            for(int k=0; k<100; k++) {
                                nivel = barra;
                                nivel.Left( m_pBufferLevels[k][0].Count() );
                                MODebug2->Log( moText(" level:") + IntToStr(k) + (moText)nivel );
                            }
                        }
                    }

					//}
					FreeImage_Unload(pImage);
					pImage = NULL;

				}
			}
		}

		m_ActualImage++;
		counter++;
		if (counter==maxfiles && maxfiles!=(-1))
			break;

	} while ( (pFile = m_pDirectory->FindNext()) );

	return true;
}
示例#14
0
unsigned int AIE::LoadTexture(const char* a_szTexture, unsigned int a_uiFormat /* = GL_RGBA */, unsigned int* a_uiWidth /* = nullptr */, unsigned int* a_uiHeight /* = nullptr */, unsigned int* a_uiBPP /* = nullptr*/)
{
	FIBITMAP* pBitmap = nullptr;

	// check the file signature and deduce its format and load it
	FREE_IMAGE_FORMAT fif = FreeImage_GetFileType(a_szTexture, 0);
	if (fif != FIF_UNKNOWN && 
		FreeImage_FIFSupportsReading(fif)) 
	{
		pBitmap = FreeImage_Load(fif, a_szTexture);
	}

	if (pBitmap == nullptr) 
	{
		printf("Error: Failed to load image '%s'!\n", a_szTexture);
		return 0;
	}

	// optionally get the image width and height
	if (a_uiWidth != nullptr)
		*a_uiWidth = FreeImage_GetWidth(pBitmap);
	if (a_uiHeight != nullptr)
		*a_uiHeight = FreeImage_GetHeight(pBitmap);

	// force the image to RGBA
	unsigned int bpp = FreeImage_GetBPP(pBitmap);
	if( a_uiBPP != nullptr )
		*a_uiBPP = bpp/8;

	FREE_IMAGE_COLOR_TYPE fi_colourType = FreeImage_GetColorType(pBitmap);
	if (fi_colourType != FIC_RGBALPHA ) 
	{
		FIBITMAP* ndib = FreeImage_ConvertTo32Bits(pBitmap);
		FreeImage_Unload(pBitmap);
		pBitmap = ndib;
		bpp = FreeImage_GetBPP(pBitmap);
		fi_colourType = FreeImage_GetColorType(pBitmap);
	}

	// get the pixel data
	BYTE* pData = FreeImage_GetBits(pBitmap);

	// try to determine data type of file (bytes/floats)
	FREE_IMAGE_TYPE fit = FreeImage_GetImageType(pBitmap);
	GLenum eType = (fit == FIT_RGBF || fit == FIT_FLOAT) ? GL_FLOAT : GL_UNSIGNED_BYTE;

	// create GL texture
	GLuint textureID;
	glGenTextures( 1, &textureID );
	glBindTexture( GL_TEXTURE_2D, textureID );
	glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, FreeImage_GetWidth(pBitmap), FreeImage_GetHeight(pBitmap), 0, a_uiFormat, eType, pData);

	// specify default filtering and wrapping
	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_REPEAT );
	glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT );

	// unbind texture
	glBindTexture( GL_TEXTURE_2D, 0 );

	// delete data
	FreeImage_Unload(pBitmap);

	return textureID;
}
示例#15
0
BOOL ImageData::LoadFromFile(const char* filename)
{
	BOOL ret = FALSE;
	FIBITMAP* dib = nullptr;

	FREE_IMAGE_FORMAT fif = FreeImage_GetFileType(filename);
	if (fif == FIF_UNKNOWN)
		fif = FreeImage_GetFIFFromFilename(filename);

	CHECK(fif != FIF_UNKNOWN && FreeImage_FIFSupportsReading(fif));

	dib = FreeImage_Load(fif, filename);
	CHECK(dib);

	mBPP = FreeImage_GetBPP(dib);
	mWidth = FreeImage_GetWidth(dib);
	mHeight = FreeImage_GetHeight(dib);

	UINT pitch = FreeImage_GetPitch(dib);
	BYTE* bits = FreeImage_GetBits(dib);
	CHECK(bits);

	switch (mBPP)
	{
	case 8:
	{
		RGBQUAD* palette = FreeImage_GetPalette(dib);
		CHECK(palette);

		mBits = new BYTE[mWidth * mHeight * 4];
		CHECK(mBits);

		for (UINT i = 0; i < mHeight; ++i) {
			for (UINT j = 0; j < mWidth; ++j) {
				UINT k = bits[i * pitch + j];
				mBits[((mHeight - 1 - i) * mWidth + j) * 4 + 0] = palette[k].rgbRed;
				mBits[((mHeight - 1 - i) * mWidth + j) * 4 + 1] = palette[k].rgbGreen;
				mBits[((mHeight - 1 - i) * mWidth + j) * 4 + 2] = palette[k].rgbBlue;
				mBits[((mHeight - 1 - i) * mWidth + j) * 4 + 3] = 255;
			}
		}
	}
	break;
	case 24:
	{
		mBits = new BYTE[mWidth * mHeight * 4];
		CHECK(mBits);

		for (UINT i = 0; i < mHeight; ++i) {
			for (UINT j = 0; j < mWidth; ++j) {
				mBits[((mHeight - 1 - i) * mWidth + j) * 4 + 0] = bits[i * pitch + j * 3 + 2];
				mBits[((mHeight - 1 - i) * mWidth + j) * 4 + 1] = bits[i * pitch + j * 3 + 1];
				mBits[((mHeight - 1 - i) * mWidth + j) * 4 + 2] = bits[i * pitch + j * 3 + 0];
				mBits[((mHeight - 1 - i) * mWidth + j) * 4 + 3] = 255;
			}
		}
	}
	break;
	case 32:
	{
		mBits = new BYTE[mWidth * mHeight * 4];
		CHECK(mBits);

		for (UINT i = 0; i < mHeight; ++i) {
			for (UINT j = 0; j < mWidth; ++j) {
				mBits[((mHeight - 1 - i) * mWidth + j) * 4 + 0] = bits[i * pitch + j * 4 + 2];
				mBits[((mHeight - 1 - i) * mWidth + j) * 4 + 1] = bits[i * pitch + j * 4 + 1];
				mBits[((mHeight - 1 - i) * mWidth + j) * 4 + 2] = bits[i * pitch + j * 4 + 0];
				mBits[((mHeight - 1 - i) * mWidth + j) * 4 + 3] = bits[i * pitch + j * 4 + 3];
			}
		}
	}
	break;
	default:
		break;
	}

	ret = TRUE;
Exit0:
	if (dib)
		FreeImage_Unload(dib);
	return ret;
}
示例#16
0
bool TextureManager::LoadTexture(const char* filename, const unsigned int texID, GLenum image_format, GLint internal_format, GLint level, GLint border)
{
	//image format
	FREE_IMAGE_FORMAT fif = FIF_UNKNOWN;
	//pointer to the image, once loaded
	FIBITMAP *dib(0);
	//pointer to the image data
	BYTE* bits(0);
	//image width and height
	unsigned int width(0), height(0);
	//OpenGL's image ID to map to
	GLuint gl_texID;
	
	//check the file signature and deduce its format
	fif = FreeImage_GetFileType(filename, 0);
	//if still unknown, try to guess the file format from the file extension
	if(fif == FIF_UNKNOWN) 
		fif = FreeImage_GetFIFFromFilename(filename);
	//if still unkown, return failure
	if(fif == FIF_UNKNOWN)
		return false;

	//check that the plugin has reading capabilities and load the file
	if(FreeImage_FIFSupportsReading(fif))
		dib = FreeImage_Load(fif, filename);
	//if the image failed to load, return failure
	if(!dib)
	{
		std::cout<<"Unable to open "<<filename<<std::endl;
		std::cout<<"Press Enter to continue"<<std::endl;
		std::cin.get();
		return false;
	}
	//retrieve the image data
	bits = FreeImage_GetBits(dib);
	//get the image width and height
	width = FreeImage_GetWidth(dib);
	height = FreeImage_GetHeight(dib);
	//if this somehow one of these failed (they shouldn't), return failure
	if((bits == 0) || (width == 0) || (height == 0))
		return false;
	
	//if this texture ID is in use, unload the current texture
	if(m_texID.find(texID) != m_texID.end())
		glDeleteTextures(1, &(m_texID[texID]));

	//generate an OpenGL texture ID for this texture
	glGenTextures(1, &gl_texID);
	//store the texture ID mapping
	m_texID[texID] = gl_texID;
	//bind to the new texture ID
	glBindTexture(GL_TEXTURE_2D, gl_texID);
	//store the texture data for OpenGL use
	glTexImage2D(GL_TEXTURE_2D, level, internal_format, width, height,
		border, image_format, GL_UNSIGNED_BYTE, bits);

	//Free FreeImage's copy of the data
	FreeImage_Unload(dib);

	//return success
	return true;
}
示例#17
0
void load_image(const char *fname) {

    // active only for static linking
    #ifdef FREEIMAGE_LIB
        FreeImage_Initialise();
    #endif

    FIBITMAP *bitmap;
    // Get the format of the image file
    FREE_IMAGE_FORMAT fif =FreeImage_GetFileType(fname, 0);

    // If the format can't be determined, try to guess the format from the file name
    if(fif == FIF_UNKNOWN) {
        fif = FreeImage_GetFIFFromFilename(fname);
    }

    // Load the data in bitmap if possible
    if(fif != FIF_UNKNOWN && FreeImage_FIFSupportsReading(fif)) {
        bitmap = FreeImage_Load(fif, fname);
    }
    else {
        bitmap = NULL;
    }

    // PROCESS IMAGE if bitmap was successfully initialized
    if(bitmap) {
        unsigned int w = FreeImage_GetWidth(bitmap);
        unsigned int h = FreeImage_GetHeight(bitmap);
        unsigned pixel_size = FreeImage_GetBPP(bitmap);

        // Get a pointer to the pixel data
        BYTE *data = (BYTE*)FreeImage_GetBits(bitmap);

        // Process only RGB and RGBA images
        if(pixel_size == 24) {
            glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, w, h, 0, GL_BGR, GL_UNSIGNED_BYTE, (GLvoid*)data);
        }
        else if (pixel_size == 32) {
            glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, w, h, 0, GL_BGRA, GL_UNSIGNED_BYTE, (GLvoid*)data);
        }
        else {
            std::cerr << "pixel size = " << pixel_size << " don't know how to process this case. I'm out!" << std::endl;
            exit(-1);
        }
        
        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
    }
    else {
        std::cerr << "Unable to load the image file " << fname  << " I'm out!" << std::endl;
        exit(-1);
    }

    // Clean bitmap;
    FreeImage_Unload(bitmap);

    // active only for static linking
    #ifdef FREEIMAGE_LIB
        FreeImage_DeInitialise();
    #endif  
}
示例#18
0
  // Load a texture from disk
  Texture::Texture(const std::string& filename,
    const TextureWrapMode wrap, const TextureFilterMode filter,
    const bool mip_map) {
    freeimage_init_lock_.lock();
    if (!freeimage_init_) {
      freeimage_init_lock_.unlock();
      throw std::wruntime_error("Texture::Texture() - ERROR: Please call "
        "initTextureSystem() before loading textures from file!");
    }
    freeimage_init_lock_.unlock();

    mip_map_ = mip_map;
    wrap_ = wrap;
    filter_ = filter;
    filename_ = filename;
    // Check if the file has any backslashes (these dont load on Mac OS X)
    size_t ind = filename_.find_first_of('\\');
    while (ind != std::string::npos) {
      filename_[ind] = '/';
      ind = filename_.find_first_of('\\');
    }
    managed_ = false;
    from_file_ = true;

    generateTextureID();

    // NEW CODE USING THE FREEIMAGE LIBRARY
    FREE_IMAGE_FORMAT fif = FIF_UNKNOWN;  //image format
	  FIBITMAP* dib = NULL;  //pointer to the image, once loaded
	  BYTE* fi_bits = NULL;  //pointer to the image data

    // check the file signature and deduce its format
    fif = FreeImage_GetFileType(filename_.c_str(), 0);
	  // if still unknown, try to guess the file format from the file extension
	  if (fif == FIF_UNKNOWN) {
      fif = FreeImage_GetFIFFromFilename(filename_.c_str());
    }
	  // if still unkown, return failure
	  if (fif == FIF_UNKNOWN) {
      throw wruntime_error(wstring(L"Texture() - ERROR: Cannot deduce format"
        L" of the file: ") + string_util::ToWideString(filename_));
    }

    // check that FreeImage has reading capabilities and if so load the file
    if (FreeImage_FIFSupportsReading(fif)) {
      dib = FreeImage_Load(fif, filename_.c_str());
    }
    //if the image failed to load, return failure
    if (!dib) {
      throw wruntime_error(wstring(L"Texture() - ERROR: FreeImage couldn't "
        L"load the file: ") + string_util::ToWideString(filename_));
    }

    // Convert everything to RGBA:
    unsigned int nbits = FreeImage_GetBPP(dib);
    if (nbits != 32) {
      FIBITMAP* old_dib = dib;
      dib = FreeImage_ConvertTo32Bits(old_dib);
      FreeImage_Unload(old_dib);
    }

    FreeImage_FlipVertical(dib);

    //retrieve the image data
	  fi_bits = FreeImage_GetBits(dib);
	  //get the image width and height
	  w_ = FreeImage_GetWidth(dib);
	  h_ = FreeImage_GetHeight(dib);
	  // if this somehow one of these failed (they shouldn't), return failure
	  if ((fi_bits == 0) || (w_ == 0) || (h_ == 0)) {
      throw wruntime_error(wstring(L"Texture() - ERROR: FreeImage couldn't "
        L"load the file: ") + string_util::ToWideString(filename));
    }

    // Copy it into memory and leave it there in case we need it later.
    bits_ = new unsigned char[w_ * h_ * 4];
    memcpy(bits_, fi_bits, sizeof(bits_[0]) * w_ * h_ * 4);

    format_internal_ = GL_RGBA;
    format_ = GL_BGRA;  // FreeImage has bits flipped!
    type_ = GL_UNSIGNED_BYTE;

    dirty_data_ = true;
    sync();  // Sync anyway on startup (fixes some shutdown bugs)

    // Free FreeImage's copy of the data
	  FreeImage_Unload(dib);

    // Unbind the texture so no one accidently makes changes to it
    GLState::glsBindTexture(GL_TEXTURE_2D, 0);
  }
	virtual bool load(const std::string& filename, Array &lat) {
		FREE_IMAGE_FORMAT type = FreeImage_GetFIFFromFilename(filename.c_str());
		if(type == FIF_UNKNOWN) {
			AL_WARN("image format not recognized: %s", filename.c_str());
			return false;
		}
		if(!FreeImage_FIFSupportsReading(type)) {
			AL_WARN("image format not supported: %s", filename.c_str());
			return false;
		}
		
		destroy();
		mImage = FreeImage_Load(type, filename.c_str(), 0);
		if (mImage == NULL) {
			AL_WARN("image failed to load: %s", filename.c_str());
			return false;
		}
		
		FREE_IMAGE_COLOR_TYPE colorType = FreeImage_GetColorType(mImage);
		switch(colorType) {
			case FIC_MINISBLACK:
			case FIC_MINISWHITE: {
					FIBITMAP *res = FreeImage_ConvertToGreyscale(mImage);
					FreeImage_Unload(mImage);
					mImage = res;
				}
				break;

			case FIC_PALETTE: {
					if(FreeImage_IsTransparent(mImage)) {
						FIBITMAP *res = FreeImage_ConvertTo32Bits(mImage);
						FreeImage_Unload(mImage);
						mImage = res;
					}
					else {
						FIBITMAP *res = FreeImage_ConvertTo24Bits(mImage);
						FreeImage_Unload(mImage);
						mImage = res;
					}
				}
				break;

			case FIC_CMYK: {
					AL_WARN("CMYK images currently not supported");
					return false;
				}
				break;

			default:
				break;
		}

		// flip vertical for OpenGL:
		//FreeImage_FlipVertical(mImage);
		
		//Freeimage is not tightly packed, so we use
		//a custom method instead of one of the Matrix
		//utility methods
		int planes = getPlanes();
		AlloTy ty = getDataType();
		int w, h;
		getDim(w, h);
		lat.format(planes, ty, w, h);
		
		Image::Format format = Image::getFormat(planes);
		switch(format) {
			case Image::LUMINANCE: {
				char *o_pix = (char *)(lat.data.ptr);
				int rowstride = lat.header.stride[1];
				for(unsigned j = 0; j < lat.header.dim[1]; ++j) {
					char *pix = (char *)FreeImage_GetScanLine(mImage, j);
					memcpy(o_pix, pix, rowstride);
					o_pix += rowstride;
				}
			}
			break;
			
			case Image::RGB: {
				switch(lat.header.type) {
					case AlloUInt8Ty: {
						char *bp = (char *)(lat.data.ptr);
						int rowstride = lat.header.stride[1];

						for(unsigned j = 0; j < lat.header.dim[1]; ++j) {
							RGBTRIPLE * pix = (RGBTRIPLE *)FreeImage_GetScanLine(mImage, j);
							Image::RGBPix<uint8_t> *o_pix = (Image::RGBPix<uint8_t> *)(bp + j*rowstride);
							for(unsigned i=0; i < lat.header.dim[0]; ++i) {
								o_pix->r = pix->rgbtRed;
								o_pix->g = pix->rgbtGreen;
								o_pix->b = pix->rgbtBlue;
								++pix;
								++o_pix;
							}
						}
					}
					break;

					case AlloFloat32Ty: {
						char *o_pix = (char *)(lat.data.ptr);
						int rowstride = lat.header.stride[1];

						for(unsigned j = 0; j < lat.header.dim[1]; ++j) {
							char *pix = (char *)FreeImage_GetScanLine(mImage, j);
							memcpy(o_pix, pix, rowstride);
							o_pix += rowstride;
						}
					}
					break;

					default: 
					break;

				}
			}
			break;
			
			case Image::RGBA: {
				switch(lat.header.type) {
					case AlloUInt8Ty: {
						char *bp = (char *)(lat.data.ptr);
						int rowstride = lat.header.stride[1];
						for(unsigned j = 0; j < lat.header.dim[1]; ++j) {
							RGBQUAD *pix = (RGBQUAD *)FreeImage_GetScanLine(mImage, j);
							Image::RGBAPix<uint8_t> *o_pix = (Image::RGBAPix<uint8_t> *)(bp + j*rowstride);
							for(unsigned i=0; i < lat.header.dim[0]; ++i) {
								o_pix->r = pix->rgbRed;
								o_pix->g = pix->rgbGreen;
								o_pix->b = pix->rgbBlue;
								o_pix->a = pix->rgbReserved;
								++pix;
								++o_pix;
							}
						}
					}
					break;

					case AlloFloat32Ty: {
						char *o_pix = (char *)(lat.data.ptr);
						int rowstride = lat.header.stride[1];
						for(unsigned j = 0; j < lat.header.dim[1]; ++j) {
							char *pix = (char *)FreeImage_GetScanLine(mImage, j);
							memcpy(o_pix, pix, rowstride);
							o_pix += rowstride;
						}
					}
					break;

					default: break;
				}
			}
			break;
			
			default: 
				AL_WARN("image data not understood");
				destroy();
				return false;
		}
		return true;
	}
示例#20
0
bool Texture::loadTexture(const char* path, bool generateMipMaps, bool defaultParameters)
{
	printf("Reading image %s\n", path);

	FREE_IMAGE_FORMAT format = FIF_UNKNOWN;
	FIBITMAP* dib(0);

	format = FreeImage_GetFileType(path, 0); // Check the file signature and deduce its format

	if (format == FIF_UNKNOWN) // If still unknown, try to guess the file format from the file extension
		format = FreeImage_GetFIFFromFilename(path);

	if (format == FIF_UNKNOWN) // If still unkown, return failure
	{
		printf("Failure(1)\n");
		return false;
	}

	// Check if the plugin has reading capabilities and load the file
	if (FreeImage_FIFSupportsReading(format))
		dib = FreeImage_Load(format, path);
	if (!dib)
	{
		printf("Failure(2)\n");
		return false;
	}

	BYTE* dataPointer = FreeImage_GetBits(dib);	// Retrieve image data

	int width = FreeImage_GetWidth(dib); // Get the image width and height
	int height = FreeImage_GetHeight(dib);
	int BPP = FreeImage_GetBPP(dib); // bytes per pixel

	// If somehow one of these failed (they shouldn't), return failure
	if (dataPointer == NULL || width == 0 || height == 0)
	{
		printf("Failure(3)\n");
		return false;
	}

	glGenTextures(1, &textureID);
	glBindTexture(GL_TEXTURE_2D, textureID);

	int texFormat = BPP == 24 ? GL_BGR : BPP == 8 ? GL_LUMINANCE : 0;
	//int internalFormat = BPP == 24 ? GL_RGB : GL_DEPTH_COMPONENT;

	glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, width, height, 0, texFormat, GL_UNSIGNED_BYTE, dataPointer);

	FreeImage_Unload(dib);

	if (defaultParameters)
	{
		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR);
	}
	if (generateMipMaps)
	{
		glGenerateMipmap(GL_TEXTURE_2D);
		mipMapsGenerated = generateMipMaps;
	}

	return true;
}
示例#21
0
/*
	Loads a heightmap from a grey scaled image which must have square dimensions.

	@param the path to the file
	@return whether the file was correctly loaded or not
*/
bool Ground::loadHeightMap(string path) {

	FREE_IMAGE_FORMAT fif = FIF_UNKNOWN;
	FIBITMAP* dib(0);

	fif = FreeImage_GetFileType(path.c_str(), 0);
	if (fif == FIF_UNKNOWN) {
		fif = FreeImage_GetFIFFromFilename(path.c_str());
	}

	if (fif == FIF_UNKNOWN) {
		std::cout << "Unknown Filetype\n";
		return false;
	}

	if (FreeImage_FIFSupportsReading(fif)) {
		dib = FreeImage_Load(fif, path.c_str());
	}

	if (!dib) {
		std::cout << "Unable to load height map\n";
		return false;
	}

	BYTE* dataPointer = FreeImage_GetBits(dib);
	hmRows = FreeImage_GetHeight(dib);
	hmCols = FreeImage_GetWidth(dib);

	// How much to increase data pointer to get to next pixel data
	unsigned int ptr_inc = FreeImage_GetBPP(dib) == 24 ? 3 : 1;

	// Length of one row in data
	unsigned int row_step = ptr_inc * hmCols;

	glGenBuffers(1, &hmdataVertexBufferID);

	vector<vector<glm::vec2>> UVcoordinates(hmRows, vector<glm::vec2>(hmCols)); 
	vector<vector<glm::vec3>> vertices(hmRows, vector<glm::vec3>(hmCols));

	float textureU = float(hmCols * 0.1);
	float textureV = float(hmRows * 0.1);

	// Calculate vertex and texture data from the value of the color in the height map
	for (int i = 0; i < hmRows; i++) {
		for (int j = 0; j < hmCols; j++) {
			float x = float(j) / float(hmCols - 1);
			float z = float(i) / float(hmRows - 1);
			float y = float(*(dataPointer + row_step * i + j * ptr_inc)) / 255.f;
			vertices[i][j] = glm::vec3(-.5 + x, y, -.5 + z);
			UVcoordinates[i][j] = glm::vec2(textureU * x, textureV * z);
			scaledHeight.insert(std::pair<std::pair<float, float>, float>(std::pair<float, float>(x, z), y));
		}
	}
	
	// Calculate the normals by getting the normals of both triangles in a quad and storing them in a 3 dimensional vector
	vector<vector<glm::vec3>> triangleNormals[2]; // Every quad has 2 triangles
	for (int i = 0; i < 2; i++) {
		triangleNormals[i] = vector<vector<glm::vec3>>(hmRows - 1, vector<glm::vec3>(hmCols - 1));
	}

	// iterate through every quad and calculate the normals
	for (int i = 0; i < hmRows - 1; i++){
		for (int j = 0; j < hmCols - 1; j++) {
			glm::vec3 triangle0[] = {vertices[i][j], vertices[i+1][j], vertices[i+1][j+1]};
			glm::vec3 triangle1[] = {vertices[i+1][j+1], vertices[i][j+1], vertices[i][j]};
			glm::vec3 triangle0Norm = glm::cross(triangle0[0] - triangle0[1], triangle0[1] - triangle0[2]);
			glm::vec3 triangle1Norm = glm::cross(triangle1[0] - triangle1[1], triangle1[1] - triangle1[2]);
			triangleNormals[0][i][j] = glm::normalize(triangle0Norm);
			triangleNormals[1][i][j] = glm::normalize(triangle1Norm);
		}
	}

	// Calculate the normal of every vertex by taking the average of each adjacent triangle's normal
	vector<vector<glm::vec3>> vertexNormals = vector<vector<glm::vec3>>(hmRows, vector<glm::vec3>(hmCols));

	for (int i = 0; i < hmRows; i++) {
		for (int j = 0; j < hmCols; j++) {

			glm::vec3 norm(0,0,0);
			
			if (i != 0 && j != 0) {
				for(int	k = 0; k < 2; k++) {
					norm += triangleNormals[k][i-1][j-1];
				}
			}
			if (i != (hmRows - 1) && j != (hmCols - 1)) {
				for (int k = 0; k < 2; k++) {
					norm += triangleNormals[k][i][j];
				}
			}
			if (i != 0 && j != (hmCols - 1)) {
				norm += triangleNormals[0][i-1][j];
			}
			if (i != (hmRows - 1) && j != 0 ) {
				norm += triangleNormals[1][i][j-1];
			}

			norm = glm::normalize(norm);

			vertexNormals[i][j] = norm;
		}
	}

	// Create the buffer for the indexed drawing
	glGenBuffers(1, &hmdataVertexBufferID);
	data.reserve(hmRows * hmCols * (2 * sizeof(glm::vec3) + sizeof(glm::vec2)));
	dataSize = hmRows * hmCols * (2 * sizeof(glm::vec3) + sizeof(glm::vec2));
	currentDataSize = 0;

	glGenBuffers(1, &hmdataVertexBufferID);

	for (int i = 0; i < hmRows; i++) {
		for (int j = 0; j < hmCols; j++) {
			addData(&vertices[i][j], sizeof(glm::vec3));
			addData(&UVcoordinates[i][j], sizeof(glm::vec2));
			addData(&vertexNormals[i][j], sizeof(glm::vec3));
		}
	}

	glGenBuffers(1, &indexVertexBufferID);
	indexSize = 0;
	currentIndexSize = 0;

	int restartIndex = hmRows * hmCols;
	
	for (int i = 0; i < hmRows - 1; i++) {
		for (int j = 0; j < hmCols; j++) {
			for (int k = 0; k < 2; k++) {
				int row = i + (1 - k);
				int index = row * hmCols + j;
				addIndexData(&index, sizeof(int));
			}
		}
		addIndexData(&restartIndex, sizeof(int));
	}
	
	glGenVertexArrays(1, &vertexArrayID);
	glBindVertexArray(vertexArrayID);

	glBindBuffer(GL_ARRAY_BUFFER, hmdataVertexBufferID);
	glBufferData(GL_ARRAY_BUFFER, data.size(), &data[0], GL_STATIC_DRAW);
	


	glEnableVertexAttribArray(0);
	glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 2*sizeof(glm::vec3)+sizeof(glm::vec2), 0);
	// Texture coordinates
	glEnableVertexAttribArray(1);
	glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, 2*sizeof(glm::vec3)+sizeof(glm::vec2), (void*)sizeof(glm::vec3));
	// Normal vectors
	glEnableVertexAttribArray(2);
	glVertexAttribPointer(2, 3, GL_FLOAT, GL_FALSE, 2*sizeof(glm::vec3)+sizeof(glm::vec2), (void*)(sizeof(glm::vec3)+sizeof(glm::vec2)));

	glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, indexVertexBufferID);
	glBufferData(GL_ELEMENT_ARRAY_BUFFER, iData.size(), &iData[0], GL_STATIC_DRAW);

	return true;
}
示例#22
0
int
main(int argc, char *argv[])
{
    printf("%s Starting...\n\n", argv[0]);

    try
    {
        std::string sFilename;
        char *filePath = sdkFindFilePath("Lena.pgm", argv[0]);

        if (filePath)
        {
            sFilename = filePath;
        }
        else
        {
            printf("Error unable to find Lena.pgm\n");
            exit(EXIT_FAILURE);
        }

        // set your own FreeImage error handler
        FreeImage_SetOutputMessage(FreeImageErrorHandler);

        cudaDeviceInit(argc, (const char **)argv);

		// Min spec is SM 1.0 devices
		if (printfNPPinfo(argc, argv, 1, 0) == false) 
		{
	        cudaDeviceReset();
			exit(EXIT_SUCCESS);
		}

        if (argc > 1)
        {
            sFilename = argv[1];
        }

        // if we specify the filename at the command line, then we only test sFilename
        // otherwise we will check both sFilename[0,1]
        int file_errors = 0;
        std::ifstream infile(sFilename.data(), std::ifstream::in);

        if (infile.good())
        {
            std::cout << "freeImageInteropNPP opened: <" << sFilename.data() << "> successfully!" << std::endl;
            file_errors = 0;
            infile.close();
        }
        else
        {
            std::cout << "freeImageInteropNPP unable to open: <" << sFilename.data() << ">" << std::endl;
            file_errors++;
            infile.close();
        }

        if (file_errors > 0)
        {
            exit(EXIT_FAILURE);
        }

        std::string sResultFilename = sFilename;

        std::string::size_type dot = sResultFilename.rfind('.');

        if (dot != std::string::npos)
        {
            sResultFilename = sResultFilename.substr(0, dot);
        }

        sResultFilename += "_boxFilterFII.pgm";

        if (argc >= 3)
        {
            sResultFilename = argv[2];
        }

        FREE_IMAGE_FORMAT eFormat = FreeImage_GetFileType(sFilename.c_str());

        // no signature? try to guess the file format from the file extension
        if (eFormat == FIF_UNKNOWN)
        {
            eFormat = FreeImage_GetFIFFromFilename(sFilename.c_str());
        }

        NPP_ASSERT(eFormat != FIF_UNKNOWN);
        // check that the plugin has reading capabilities ...
        FIBITMAP *pBitmap;

        if (FreeImage_FIFSupportsReading(eFormat))
        {
            pBitmap = FreeImage_Load(eFormat, sFilename.c_str());
        }

        NPP_ASSERT(pBitmap != 0);
        // Dump the bitmap information to the console
        std::cout << (*pBitmap) << std::endl;
        // make sure this is an 8-bit single channel image
        NPP_ASSERT(FreeImage_GetColorType(pBitmap) == FIC_MINISBLACK);
        NPP_ASSERT(FreeImage_GetBPP(pBitmap) == 8);

        unsigned int nImageWidth  = FreeImage_GetWidth(pBitmap);
        unsigned int nImageHeight = FreeImage_GetHeight(pBitmap);
        unsigned int nSrcPitch    = FreeImage_GetPitch(pBitmap);
        unsigned char *pSrcData  = FreeImage_GetBits(pBitmap);

        int nSrcPitchCUDA;
        Npp8u *pSrcImageCUDA = nppiMalloc_8u_C1(nImageWidth, nImageHeight, &nSrcPitchCUDA);
        NPP_ASSERT_NOT_NULL(pSrcImageCUDA);
        // copy image loaded via FreeImage to into CUDA device memory, i.e.
        // transfer the image-data up to the GPU's video-memory
        NPP_CHECK_CUDA(cudaMemcpy2D(pSrcImageCUDA, nSrcPitchCUDA, pSrcData, nSrcPitch,
                                    nImageWidth, nImageHeight, cudaMemcpyHostToDevice));

        // define size of the box filter
        const NppiSize  oMaskSize   = {7, 7};
        const NppiPoint oMaskAchnor = {0, 0};
        // compute maximal result image size
        const NppiSize  oSizeROI = {nImageWidth  - (oMaskSize.width - 1),
                                    nImageHeight - (oMaskSize.height - 1)
                                   };
        // allocate result image memory
        int nDstPitchCUDA;
        Npp8u *pDstImageCUDA = nppiMalloc_8u_C1(oSizeROI.width, oSizeROI.height, &nDstPitchCUDA);
        NPP_ASSERT_NOT_NULL(pDstImageCUDA);
        NPP_CHECK_NPP(nppiFilterBox_8u_C1R(pSrcImageCUDA, nSrcPitchCUDA, pDstImageCUDA, nDstPitchCUDA,
                                           oSizeROI, oMaskSize, oMaskAchnor));
        // create the result image storage using FreeImage so we can easily
        // save
        FIBITMAP *pResultBitmap = FreeImage_Allocate(oSizeROI.width, oSizeROI.height, 8 /* bits per pixel */);
        NPP_ASSERT_NOT_NULL(pResultBitmap);
        unsigned int nResultPitch   = FreeImage_GetPitch(pResultBitmap);
        unsigned char *pResultData = FreeImage_GetBits(pResultBitmap);

        NPP_CHECK_CUDA(cudaMemcpy2D(pResultData, nResultPitch, pDstImageCUDA, nDstPitchCUDA,
                                    oSizeROI.width, oSizeROI.height, cudaMemcpyDeviceToHost));
        // now save the result image
        bool bSuccess;
        bSuccess = FreeImage_Save(FIF_PGM, pResultBitmap, sResultFilename.c_str(), 0) == TRUE;
        NPP_ASSERT_MSG(bSuccess, "Failed to save result image.");

        //free nppiImage
        nppiFree(pSrcImageCUDA);
        nppiFree(pDstImageCUDA);

        cudaDeviceReset();
        exit(EXIT_SUCCESS);
    }
    catch (npp::Exception &rException)
    {
        std::cerr << "Program error! The following exception occurred: \n";
        std::cerr << rException << std::endl;
        std::cerr << "Aborting." << std::endl;
        exit(EXIT_FAILURE);
    }
    catch (...)
    {
        std::cerr << "Program error! An unknow type of exception occurred. \n";
        std::cerr << "Aborting." << std::endl;
        exit(EXIT_FAILURE);
    }

    exit(EXIT_SUCCESS);
}
示例#23
0
bool sr::Texture::LoadFromFile(const std::string& relativePath, const sr::FileSystem& fileSystem)
{
    Unload();
    Name(relativePath);
    
    const std::string fullPath   = fileSystem.GetFullPath(relativePath);
    const char* filename         = fullPath.c_str();
    const GLenum image_format    = GL_RGB;    // format the image is in
    const GLint  internal_format = GL_RGB;    // format to store the image in
    const GLint  level           = 0;	        // mipmapping level
    const GLint  border          = 0;	        // border size
        	
	//check the file signature and deduce its format
	FREE_IMAGE_FORMAT fif = FreeImage_GetFileType(filename, 0);

    // Try to guess the file format from the file extension:
	if(fif == FIF_UNKNOWN) 
		fif = FreeImage_GetFIFFromFilename(filename);

	// if still unkown, return failure
	if(fif == FIF_UNKNOWN || !FreeImage_FIFSupportsReading(fif))
		return false;

	//check that the plugin has reading capabilities and load the file
    FIBITMAP* const dib = FreeImage_Load(fif, filename, PNG_DEFAULT);
	if(!dib) 
        return false;
    
	BYTE* const bits = FreeImage_GetBits(dib);
	const unsigned int width = FreeImage_GetWidth(dib);
	const unsigned int height = FreeImage_GetHeight(dib);
	
	// if this somehow one of these failed (they shouldn't), return failure
	if((bits == nullptr) || (width == 0) || (height == 0))
		return false;
	
	// Calculate the number of bytes per pixel (3 for 24-bit or 4 for 32-bit)
	const int bpp = FreeImage_GetLine(dib) / FreeImage_GetWidth(dib);

	// Exchange red and blue channel because FreeImage loads in BGRA format; while we need it as RGBA:
	for(unsigned y = 0; y < height; ++y)
	{
		BYTE* line = FreeImage_GetScanLine(dib, y);

		for( unsigned x = 0; x < width; ++x ) 
		{
			const BYTE r = line[FI_RGBA_BLUE];			
			const BYTE b = line[FI_RGBA_RED];
			line[FI_RGBA_RED]  = r;
			line[FI_RGBA_BLUE] = b;

			// jump to next pixel
			line += bpp;
		}
	}

    // Generate
	glGenTextures(1, &id);
	glBindTexture(GL_TEXTURE_2D, id);
	glTexImage2D(GL_TEXTURE_2D, level, internal_format, width, height, border, image_format, GL_UNSIGNED_BYTE, bits);

    // Configure
	glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
	glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
    	
	GLfloat maxAniso(0.0f);
	glGetFloatv(GL_MAX_TEXTURE_MAX_ANISOTROPY_EXT, &maxAniso);
	glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAX_ANISOTROPY_EXT, maxAniso);

	// Free FreeImage's copy of the data
	FreeImage_Unload(dib);

    if(id != 0)
    {
        size = glm::uvec2(width, height);
        Loaded(true);
        return true;
    }
    else
    {
        return false;
    }
}
示例#24
0
        Texture* TextureManager::addTexture( const std::string& filename )
        {
            Texture* ret = nullptr;

            FREE_IMAGE_FORMAT fif = FIF_UNKNOWN;
            FIBITMAP* dib = nullptr; // TODO This name is nonsense, change it

            // Find format from file signature
            fif = FreeImage_GetFileType( filename.c_str(), 0 );

            if ( FIF_UNKNOWN == fif )
            {
                // Find format from file extension
                fif = FreeImage_GetFIFFromFilename( filename.c_str() );
            }

            if ( FIF_UNKNOWN == fif )
            {
                // Still unknown
                std::string error = "Cannot determine " + filename + " image format.";
                LOG( logERROR ) << error;
                CORE_ASSERT( 0, error.c_str() );

                return nullptr;
            }

            if ( FreeImage_FIFSupportsReading( fif ) )
            {
                dib = FreeImage_Load( fif, filename.c_str() );
            }

            std::string error = "Something went wrong while trying to load " + filename + ".";
            //CORE_ASSERT(dib, error.c_str());

            if ( nullptr == dib )
            {
                LOG( logERROR ) << error;
                return nullptr;
            }

            ret = new Texture( filename, GL_TEXTURE_2D );
            unsigned char* data = FreeImage_GetBits( dib );

            int bpp = FreeImage_GetBPP( dib );
            int format = ( bpp == 24 ? GL_BGR : 0 ); // TODO Handle other formats
            int internal = ( bpp == 24 ? GL_RGB : 0 ); // TODO Handle other formats
            int w = FreeImage_GetWidth( dib );
            int h = FreeImage_GetHeight( dib );

            // FIXME(Charly): Use VLOG instead of the check
            if ( m_verbose )
            {
                LOG( logINFO ) << "Image stats (" << filename << ") :\n"
                               << "\tBPP    : 0x" << std::hex << bpp << std::dec << std::endl
                               << "\tFormat : 0x" << std::hex << format << std::dec << std::endl
                               << "\tSize   : " << w << ", " << h;
            }


            CORE_ASSERT( data, "Data is null" );

            ret->initGL( internal, w, h, format, GL_UNSIGNED_BYTE, data );
            ret->genMipmap( GL_LINEAR_MIPMAP_LINEAR, GL_LINEAR );

            m_textures.insert( TexturePair( filename, ret ) );

            FreeImage_Unload( dib );

            return ret;
        }
示例#25
0
unsigned int LoadTexture(const char* a_szTexture) 
{ 
	FIBITMAP* pBitmap = nullptr;
 
	// Determime File Type from File Signature
	FREE_IMAGE_FORMAT fif = FreeImage_GetFileType(a_szTexture, 0); 
 
	// Success
	if (fif != FIF_UNKNOWN && FreeImage_FIFSupportsReading(fif)) 
	{ 
		pBitmap = FreeImage_Load(fif, a_szTexture); 
	} 
 
	// Failure
	if (pBitmap == nullptr) 
	{ 
		printf("Error: Failed to load image '%s'!\n", a_szTexture); 
		return 0; 
	} 
 
	// Force the image to RGBA
 
	// Get size of pixel in bits
	unsigned int bpp = FreeImage_GetBPP(pBitmap);
	
	/*
 
	// How does this conversion to RGBA work?
	if( a_uiBPP != nullptr )
	{
		*a_uiBPP = bpp/8;
 
		//RGBA has 8 bits per color channel...
	}
 
	*/
 
	// Get Color Type
	FREE_IMAGE_COLOR_TYPE fi_colourType = FreeImage_GetColorType(pBitmap); 
 
	if (fi_colourType != FIC_RGBALPHA ) 
	{ 
		FIBITMAP* ndib = FreeImage_ConvertTo32Bits(pBitmap); 
		FreeImage_Unload(pBitmap); 
		pBitmap = ndib; 
		bpp = FreeImage_GetBPP(pBitmap); 
		fi_colourType = FreeImage_GetColorType(pBitmap); 
	} 
 
	// get the pixel data 
	BYTE* pData = FreeImage_GetBits(pBitmap); 
 
	// try to determine data type of file (bytes/floats) 
	FREE_IMAGE_TYPE fit = FreeImage_GetImageType(pBitmap);
 
	// VARIABLE	 =   (		CONDITION TO EVALUATE      ) ? IF_TRUE :	IF_FALSE	;
	GLenum eType = (fit == FIT_RGBF || fit == FIT_FLOAT) ? GL_FLOAT:GL_UNSIGNED_BYTE;
 
	// Create variable to store OGL Tex ID
	GLuint textureID;
	
	// Generate OGL Tex ID
	glGenTextures( 1, &textureID ); 
	
	// Bind Texture for Use by using the OGL Tex DI
	glBindTexture( GL_TEXTURE_2D, textureID ); 
	
	// Texturing allows elements of an image array to be read by shaders.
 
	glTexImage2D( GL_TEXTURE_2D,				// TARGET
				  0,							// level of detail
				  GL_RGBA,						// color format
				  FreeImage_GetWidth(pBitmap),	// width
				  FreeImage_GetHeight(pBitmap),	// height
				  0,							// border (must be 0)
				  fi_colourType,					// pixel data format - i.e. RGBA
				  eType,						// pixel data type
				  pData);						// data
 
	// specify default filtering and wrapping 
	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 ); 
 
	// unbind texture 
	glBindTexture( GL_TEXTURE_2D, 0 ); 
 
	// delete data 
	FreeImage_Unload(pBitmap);
 
	return textureID; 
}
示例#26
0
	bool FreeImage::onLoad() {

		switch ( this -> loadingType ) {
			case LoadingType::EMPTY:
				{
					this -> freeImage = FreeImage_Allocate( this -> size.x, this -> size.y, this -> BPP, 0, 0, 0 );
					break;
				}
			case LoadingType::FILE: 
				{
					// Check the file signature and deduce its format.
					#ifdef WIN32
					FREE_IMAGE_FORMAT imageFormat = FreeImage_GetFileTypeU( fileNameW.toCString(), 0 );
					#else
					FREE_IMAGE_FORMAT imageFormat = FreeImage_GetFileType( fileName.toCString(), 0 );
					#endif

					// If still unknown, try to guess the file format from the file extension.  
					if ( imageFormat == FIF_UNKNOWN ) {
						#ifdef WIN32
						imageFormat = FreeImage_GetFIFFromFilenameU( fileNameW.toCString() );
						#else
						imageFormat = FreeImage_GetFIFFromFilename( fileName.toCString() );
						#endif
					}

					// If still unknown, return failure.  
					if ( imageFormat == FIF_UNKNOWN ) {
						error( String( "Free Image was unable to detect the file format : " ) << fileName );
						return false;
					}

					// Check that the plugin has reading capabilities and load the file.  
					if ( FreeImage_FIFSupportsReading( imageFormat ) ) {
						#ifdef WIN32
						this -> freeImage = FreeImage_LoadU( imageFormat, fileNameW.toCString() );
						#else
						this -> freeImage = FreeImage_Load( imageFormat, fileName.toCString() );
						#endif
					}

					if ( this -> freeImage == NULL ) {
						error( String( "Free Image was unable to load the picture : " ) << fileName );
						return false;
					}
					if ( this -> size.x == 0 || this -> size.y == 0 ) {
						this -> size.x = FreeImage_GetWidth( this -> freeImage );
						this -> size.y = FreeImage_GetHeight( this -> freeImage );
					}


					if ( this -> loadingFormat == Format::UNDEFINED ) {
						switch ( FreeImage_GetColorType( this -> freeImage ) ) {
							case FIC_PALETTE:
								_updateFormat( Format::R );
								break;
							case FIC_RGB:
								_updateFormat( Format::RGB );
								break;
							default:
								_updateFormat( Format::RGBA );
								break;
						}
					}

					log( this -> fileName << this -> size << " has been loaded successfully !" );
					break;
				}

		}


		//if we have to flip vertically.
		if ( this -> invertY )
			FreeImage_FlipVertical( this -> freeImage );
		//Change BPP
		if ( this -> BPP != FreeImage_GetBPP( this -> freeImage ) )
			_updateBPP();
		//resize
		if ( this -> size != Math::Vec2<Size>( FreeImage_GetWidth( this -> freeImage ), FreeImage_GetHeight( this -> freeImage ) ) )
			_updateSize();

		this -> stride = FreeImage_GetPitch( this -> freeImage );
		return true;
	}
static void saveImage(ofPixels_<PixelType> & pix, string fileName, ofImageQualityType qualityLevel) {
	ofInitFreeImage();
	if (pix.isAllocated() == false){
		ofLog(OF_LOG_ERROR,"error saving image - pixels aren't allocated");
		return;
	}

	#ifdef TARGET_LITTLE_ENDIAN
	if(sizeof(PixelType) == 1) {
		pix.swapRgb();
	}
	#endif

	FIBITMAP * bmp	= getBmpFromPixels(pix);

	#ifdef TARGET_LITTLE_ENDIAN
	if(sizeof(PixelType) == 1) {
		pix.swapRgb();
	}
	#endif
	
	fileName = ofToDataPath(fileName);
	FREE_IMAGE_FORMAT fif = FIF_UNKNOWN;
	fif = FreeImage_GetFileType(fileName.c_str(), 0);
	if(fif == FIF_UNKNOWN) {
		// or guess via filename
		fif = FreeImage_GetFIFFromFilename(fileName.c_str());
	}
	if((fif != FIF_UNKNOWN) && FreeImage_FIFSupportsReading(fif)) {
		if(fif == FIF_JPEG) {
			int quality = JPEG_QUALITYSUPERB;
			switch(qualityLevel) {
				case OF_IMAGE_QUALITY_WORST: quality = JPEG_QUALITYBAD; break;
				case OF_IMAGE_QUALITY_LOW: quality = JPEG_QUALITYAVERAGE; break;
				case OF_IMAGE_QUALITY_MEDIUM: quality = JPEG_QUALITYNORMAL; break;
				case OF_IMAGE_QUALITY_HIGH: quality = JPEG_QUALITYGOOD; break;
				case OF_IMAGE_QUALITY_BEST: quality = JPEG_QUALITYSUPERB; break;
			}
			FreeImage_Save(fif, bmp, fileName.c_str(), quality);
		} else {
			if(qualityLevel != OF_IMAGE_QUALITY_BEST) {
				ofLogWarning() << "ofImageCompressionType only applies to JPEG images, ignoring value";
			}
			
			if (fif == FIF_GIF) {
				FIBITMAP* convertedBmp;
				if(pix.getImageType() == OF_IMAGE_COLOR_ALPHA) {
					// this just converts the image to grayscale so it can save something
					convertedBmp = FreeImage_ConvertTo8Bits(bmp);
				} else {
					// this will create a 256-color palette from the image
					convertedBmp = FreeImage_ColorQuantize(bmp, FIQ_NNQUANT);
				}
				FreeImage_Save(fif, convertedBmp, fileName.c_str());
				if (convertedBmp != NULL){
					FreeImage_Unload(convertedBmp);
				}
			} else {
				FreeImage_Save(fif, bmp, fileName.c_str());
			}
		}
	}

	if (bmp != NULL){
		FreeImage_Unload(bmp);
	}
}
示例#28
0
		Int32 loadTexture(Texture *out_texture, const char *fileAddress)
		{
			__BLITZ_ASSERT(out_texture);
			__BLITZ_ASSERT(fileAddress);
			auto existingTexture = textureList.find(std::string(fileAddress));
			if (existingTexture != textureList.end())
			{
				*out_texture = existingTexture->second;
				return 0;
			}
			FREE_IMAGE_FORMAT freeImageFormat;
			freeImageFormat = FreeImage_GetFileType(fileAddress, 0);
			if (freeImageFormat == FIF_UNKNOWN)
			{
				freeImageFormat = FreeImage_GetFIFFromFilename(fileAddress);
			}
			if (freeImageFormat == FIF_UNKNOWN)
			{
				__BLITZ_THROW_ERROR("Failed to load image \"" +
					std::string(fileAddress) + "\" : Image format is not supported.");
				return 1;
			}
			Bool loadAlphaChannel = 0;
			switch (freeImageFormat)
			{
			case FIF_BMP:
			case FIF_GIF:
			case FIF_JPEG:
				loadAlphaChannel = 0;
				break;
			case FIF_DDS:
			case FIF_PNG:
			case FIF_TARGA:
				loadAlphaChannel = 1;
				break;
			}
			if (FreeImage_FIFSupportsReading(freeImageFormat) == 0)
			{
				__BLITZ_THROW_ERROR("Failed to load image \"" +
					std::string(fileAddress) +
					"\" : Reading from this image format is not supported.");
				return 1;
			}
			FIBITMAP *freeImageBitmap = FreeImage_Load(freeImageFormat, fileAddress, 0);
			if (freeImageBitmap == 0)
			{
				__BLITZ_THROW_ERROR("Failed to load image \"" +
					std::string(fileAddress) + "\" : Failed to load image file.");
				return 1;
			}
			BYTE *imageData = FreeImage_GetBits(freeImageBitmap);
			if (imageData == 0)
			{
				__BLITZ_THROW_ERROR("Failed to load image \"" +
					std::string(fileAddress) + "\" : Failed to get image data.");
				return 1;
			}
			Int32 imageWidth = FreeImage_GetWidth(freeImageBitmap),
				imageHeight = FreeImage_GetHeight(freeImageBitmap);
			if (imageWidth <= 0 || imageHeight <= 0)
			{
				__BLITZ_THROW_ERROR("Failed to load image \"" +
					std::string(fileAddress) + "\" : Image dimensions are invalid.");
				return 1;
			}
			glGenTextures(1, out_texture);
			glBindTexture(GL_TEXTURE_2D, *out_texture);
			GLint imageFormat = loadAlphaChannel ? GL_BGRA : GL_BGR;
			glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, imageWidth, imageHeight, 0,
				imageFormat, GL_UNSIGNED_BYTE, imageData);
			glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
			glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
			glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
			glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
			glBindTexture(GL_TEXTURE_2D, 0);
			FreeImage_Unload(freeImageBitmap);
			std::pair<std::string, Texture> newPair =
				std::pair<std::string, Texture>(fileAddress, *out_texture);
			textureList.insert(newPair);
			blitz::__debug::throwMessage("Image \"" + std::string(fileAddress) +
				"\" loaded.");
			return 0;
		}
示例#29
0
  void Texture::loadImFromFile(const std::string& filename, uint8_t*& im, 
    uint32_t& width, uint32_t& height, uint32_t& n_chan) {
    freeimage_init_lock_.lock();
    if (!freeimage_init_) {
      freeimage_init_lock_.unlock();
      throw std::wruntime_error("Texture::Texture() - ERROR: Please call "
        "initTextureSystem() before loading textures from file!");
    }
    freeimage_init_lock_.unlock();

    // Check if the file has any backslashes (these dont load on Mac OS X)
    std::string file = filename;
    size_t ind = file.find_first_of('\\');
    while (ind != std::string::npos) {
      file[ind] = '/';
      ind = file.find_first_of('\\');
    }

    // NEW CODE USING THE FREEIMAGE LIBRARY
    FREE_IMAGE_FORMAT fif = FIF_UNKNOWN;  //image format
	  FIBITMAP* dib = NULL;  //pointer to the image, once loaded
	  BYTE* fi_bits = NULL;  //pointer to the image data

    // check the file signature and deduce its format
    fif = FreeImage_GetFileType(file.c_str(), 0);
	  // if still unknown, try to guess the file format from the file extension
	  if (fif == FIF_UNKNOWN) {
      fif = FreeImage_GetFIFFromFilename(file.c_str());
    }
	  // if still unkown, return failure
	  if (fif == FIF_UNKNOWN) {
      throw wruntime_error(wstring(L"Texture() - ERROR: Cannot deduce format"
        L" of the file: ") + string_util::ToWideString(file));
    }

    // check that FreeImage has reading capabilities and if so load the file
    if (FreeImage_FIFSupportsReading(fif)) {
      dib = FreeImage_Load(fif, file.c_str());
    }
    //if the image failed to load, return failure
    if (!dib) {
      throw wruntime_error(wstring(L"Texture() - ERROR: FreeImage couldn't "
        L"load the file: ") + string_util::ToWideString(file));
    }

    n_chan = FreeImage_GetBPP(dib) / 8;

    FreeImage_FlipVertical(dib);

    //retrieve the image data
	  fi_bits = FreeImage_GetBits(dib);
	  //get the image width and height
	  width = FreeImage_GetWidth(dib);
	  height = FreeImage_GetHeight(dib);
	  // if this somehow one of these failed (they shouldn't), return failure
	  if ((fi_bits == 0) || (width == 0) || (height == 0)) {
      throw wruntime_error(wstring(L"Texture() - ERROR: FreeImage couldn't "
        L"load the file: ") + string_util::ToWideString(filename));
    }

    // Copy it into memory and leave it there in case we need it later.
    im = new uint8_t[width * height * n_chan];
    memcpy(im, fi_bits, sizeof(im[0]) * width * height * n_chan);

    // Unfortunately the R and B bits get flipped:
    // http://sourceforge.net/p/freeimage/bugs/172/
    if (n_chan > 1) {
      uint8_t* tmp = new uint8_t[n_chan];
      for (uint32_t v = 0; v < height; v++) {
        for (uint32_t u = 0; u < width; u++) {
          for (uint32_t i = 0; i < n_chan; i++) {
            tmp[n_chan - i - 1] = im[(v * width + u) * n_chan + i];
          }
          for (uint32_t i = 0; i < n_chan; i++) {
            im[(v * width + u) * n_chan + i] = tmp[i];
          }
        }
      }
      delete[] tmp;
    }
  }
示例#30
0
void Image::_load(string sFilename)
{
	errlog << "Load " << sFilename << endl;
	//image format
	FREE_IMAGE_FORMAT fif = FIF_UNKNOWN;
	//pointer to the image, once loaded
	FIBITMAP *dib(0);
	//pointer to the image data
	BYTE* bits(0);
	//image width and height
	unsigned int width(0), height(0);
	
	//check the file signature and deduce its format
	fif = FreeImage_GetFileType(sFilename.c_str(), 0);
	//if still unknown, try to guess the file format from the file extension
	if(fif == FIF_UNKNOWN) 
		fif = FreeImage_GetFIFFromFilename(sFilename.c_str());
	//if still unkown, return failure
	if(fif == FIF_UNKNOWN)
	{
		errlog << "Unknown image type for file " << sFilename << endl;
		return;
	}
  
	//check that the plugin has reading capabilities and load the file
	if(FreeImage_FIFSupportsReading(fif))
		dib = FreeImage_Load(fif, sFilename.c_str());
	else
		errlog << "File " << sFilename << " doesn't support reading." << endl;
	//if the image failed to load, return failure
	if(!dib)
	{
		errlog << "Error loading image " << sFilename.c_str() << endl;
		return;
	}  
	//retrieve the image data
  
	//get the image width and height
	width = FreeImage_GetWidth(dib);
	height = FreeImage_GetHeight(dib);
  
	int w = power_of_two(width);
	int h = power_of_two(height);
	int mode, modeflip;
	if(FreeImage_GetBPP(dib) == 24) // RGB 24bit
	{
		mode = GL_RGB;
		modeflip = GL_BGR;
	}
	else if(FreeImage_GetBPP(dib) == 32)  // RGBA 32bit
	{
		mode = GL_RGBA;
		modeflip = GL_BGRA;
	}
	FIBITMAP *bitmap2 = FreeImage_Allocate(w, h, FreeImage_GetBPP(dib));
	FreeImage_Paste(bitmap2, dib, 0, 0, 255);
	FreeImage_FlipVertical(bitmap2);  //Apparently, FreeImage handles this strangely. Flipping beforehand doesn't work right.
	FreeImage_Unload(dib);
  
	bits = FreeImage_GetBits(bitmap2);	//if this somehow one of these failed (they shouldn't), return failure
	if((bits == 0) || (width == 0) || (height == 0))
	{
		errlog << "Something went terribly horribly wrong with getting image bits; just sit and wait for the singularity" << endl;
		return;
	}
  
	//generate an OpenGL texture ID for this texture
	m_iWidth = width;
	m_iHeight = height;
	m_iRealWidth = w;
	m_iRealHeight = h;
	glGenTextures(1, &m_hTex);
	//bind to the new texture ID
	glBindTexture(GL_TEXTURE_2D, m_hTex);
	//store the texture data for OpenGL use
	glTexImage2D(GL_TEXTURE_2D, 0, mode, w, h, 0, modeflip, GL_UNSIGNED_BYTE, bits);
  
	//Free FreeImage's copy of the data
	FreeImage_Unload(bitmap2);
}