bool TextureManager::LoadTexture(const char *filename, const unsigned int texID, bool generate, GLenum target, 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) 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])); if (generate) { // 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(target, gl_texID); } // store the texture data for OpenGL use glTexImage2D(target, 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; }
bool CTexture::loadTexture2D(std::string sTexturePath, bool bGenerateMipMaps) { FREE_IMAGE_FORMAT fif = FIF_UNKNOWN; FIBITMAP* dib(0); fif = FreeImage_GetFileType(sTexturePath.c_str(), 0); // 检查文件签名,推导其格式 if(fif == FIF_UNKNOWN) fif = FreeImage_GetFIFFromFilename(sTexturePath.c_str()); // 从扩展名猜测格式 if(fif == FIF_UNKNOWN) return false; if(FreeImage_FIFSupportsReading(fif)) dib = FreeImage_Load(fif, sTexturePath.c_str()); if(!dib) return false; GLubyte* bDataPointer = FreeImage_GetBits(dib); if(bDataPointer == NULL || FreeImage_GetWidth(dib) == 0 || FreeImage_GetHeight(dib) == 0) return false; GLenum format = FreeImage_GetBPP(dib) == 24 ? GL_BGR : FreeImage_GetBPP(dib) == 8 ? GL_LUMINANCE : 0; createFromData(bDataPointer, FreeImage_GetWidth(dib), FreeImage_GetHeight(dib), FreeImage_GetBPP(dib), format, bGenerateMipMaps); FreeImage_Unload(dib); m_sTexturePath = sTexturePath; return true; }
void FreeImageGifData::add24bitBGRDataPage(int width, int height, BYTE* pData) { FIBITMAP* newBitmap = FreeImage_Allocate(width, height, 24, 0x0000FF, 0x00FF00, 0xFF0000); BYTE* bitmapData = FreeImage_GetBits(newBitmap); memcpy(bitmapData, pData, width * height * 3); //Set metadata FIBITMAP* convBitmap = FreeImage_ColorQuantizeEx(newBitmap, FIQ_WUQUANT, 256); FITAG* delayTag = FreeImage_CreateTag(); FreeImage_SetMetadata(FIMD_ANIMATION, convBitmap, NULL, NULL); LONG delayVal = 20; if (delayTag) { FreeImage_SetTagKey(delayTag, "FrameTime"); FreeImage_SetTagType(delayTag, FIDT_LONG); FreeImage_SetTagCount(delayTag, 1); FreeImage_SetTagLength(delayTag, 4); FreeImage_SetTagValue(delayTag, &delayVal); FreeImage_SetMetadata(FIMD_ANIMATION, convBitmap, FreeImage_GetTagKey(delayTag), delayTag); FreeImage_DeleteTag(delayTag); } FreeImage_AppendPage(m_gifHandle, convBitmap); int pCount = FreeImage_GetPageCount(m_gifHandle); FreeImage_Unload(newBitmap); FreeImage_Unload(convBitmap); }
GLubyte* Texture::loadToBitmap(std::string path, bool flip) { const char* pathCStr = path.c_str(); FREE_IMAGE_FORMAT format = FIF_UNKNOWN; format = FreeImage_GetFileType(pathCStr); if (format == FIF_UNKNOWN) format = FreeImage_GetFIFFromFilename(pathCStr); if (format == FIF_UNKNOWN) { std::cout << "Failed to load image at " << pathCStr << std::endl; return nullptr; } if (!FreeImage_FIFSupportsReading(format)) { std::cout << "Detected image format cannot be read! " << pathCStr << std::endl; return nullptr; } m_bitmap = FreeImage_Load(format, pathCStr); if (flip) FreeImage_FlipVertical(m_bitmap); GLint bitsPerPixel = FreeImage_GetBPP(m_bitmap); if (bitsPerPixel == 32) m_bitmap32 = m_bitmap; else m_bitmap32 = FreeImage_ConvertTo32Bits(m_bitmap); m_width = FreeImage_GetWidth(m_bitmap32); m_height = FreeImage_GetHeight(m_bitmap32); return FreeImage_GetBits(m_bitmap32); }
GLuint TextureFromFile(const char* filename) { FREE_IMAGE_FORMAT fileFormat = FIF_UNKNOWN; FIBITMAP *image(0); BYTE* bits(0); unsigned int width(0), height(0); fileFormat = FreeImage_GetFileType(filename, 0); image = FreeImage_Load(fileFormat, filename); if(!image) return 0; bits = FreeImage_GetBits(image); width = FreeImage_GetWidth(image); height = FreeImage_GetHeight(image); GLuint tex; glGenTextures(1, &tex); glBindTexture(GL_TEXTURE_2D, tex); gluBuild2DMipmaps(GL_TEXTURE_2D, GL_RGB, width, height, GL_BGR, GL_UNSIGNED_BYTE, bits); glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MIN_FILTER,GL_LINEAR); glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MAG_FILTER,GL_LINEAR); FreeImage_Unload(image); return tex; }
bool ZitexConverter::convert(const QString & inFileName, const ConfigDao & configuration) { auto inFileNameStdStr = inFileName.toStdString(); Zitex::Reader reader; Zitex::Reader::Data data; reader.readFromFile(inFileNameStdStr, data); for (uint32_t it = 0; it < data.header->texImagesNum; ++it) { Zitex::TexImageHeader * texImageHeader = data.texImages[it].header; if (texImageHeader->level == 0) { auto width = texImageHeader->width; auto height = texImageHeader->height; FIBITMAP * fiBitmap = FreeImage_Allocate(width, height, 32); squish::DecompressImage(FreeImage_GetBits(fiBitmap), width, height, data.texImages[it].data, data.header->squishFlags); // section(".", 0, -2) copyes from begin to 2nd section from end. // The first section from end is the extension std::string outFileNameStdStr = inFileName.section(".", 0, -2).append(".png").toStdString(); FreeImage_FlipVertical(fiBitmap); FreeImage_Save(FIF_PNG, fiBitmap, outFileNameStdStr.c_str()); FreeImage_Unload(fiBitmap); } } }
FIBITMAP* getBmpFromPixels(ofPixels_<PixelType> &pix){ PixelType* pixels = pix.getData(); unsigned int width = pix.getWidth(); unsigned int height = pix.getHeight(); unsigned int bpp = pix.getBitsPerPixel(); FREE_IMAGE_TYPE freeImageType = getFreeImageType(pix); FIBITMAP* bmp = FreeImage_AllocateT(freeImageType, width, height, bpp); unsigned char* bmpBits = FreeImage_GetBits(bmp); if(bmpBits != NULL) { int srcStride = width * pix.getBytesPerPixel(); int dstStride = FreeImage_GetPitch(bmp); unsigned char* src = (unsigned char*) pixels; unsigned char* dst = bmpBits; if(srcStride != dstStride){ for(int i = 0; i < (int)height; i++) { memcpy(dst, src, srcStride); src += srcStride; dst += dstStride; } }else{ memcpy(dst,src,dstStride*height); } } else { ofLogError("ofImage") << "getBmpFromPixels(): unable to get FIBITMAP from ofPixels"; } // ofPixels are top left, FIBITMAP is bottom left FreeImage_FlipVertical(bmp); return bmp; }
int _tmain(int argc, _TCHAR* argv[]) { const char* filename = "1.jpg"; FREE_IMAGE_FORMAT fif = FreeImage_GetFileType(filename, 0); FIBITMAP *dib(0); //pointer to the image data BYTE* bits(0); //image width and height unsigned int width(0), height(0); if(fif == FIF_UNKNOWN) fif = FreeImage_GetFIFFromFilename(filename); if(fif == FIF_UNKNOWN) return 1; if(FreeImage_FIFSupportsReading(fif)) dib = FreeImage_Load(fif, filename); //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 1; return 0; }
Texture::Texture(const char* file) { FREE_IMAGE_FORMAT fif = FIF_UNKNOWN; FIBITMAP* dib = nullptr; fif = FreeImage_GetFileType(file, 0); if (fif == FIF_UNKNOWN) fif = FreeImage_GetFIFFromFilename(file); if (fif != FIF_UNKNOWN) { if (FreeImage_FIFSupportsReading(fif)) dib = FreeImage_Load(fif, file); BYTE* pixels = FreeImage_GetBits(dib); int width = FreeImage_GetWidth(dib); int height = FreeImage_GetHeight(dib); int bits = FreeImage_GetBPP(dib); int size = width * height * (bits / 8); BYTE* result = new BYTE[size]; memcpy(result, pixels, size); FreeImage_Unload(dib); glGenTextures(1, &m_ID); glBindTexture(GL_TEXTURE_2D, m_ID); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, result ? result : NULL); glBindTexture(GL_TEXTURE_2D, 0); } else { m_ID = -1; } }
GLuint Engine::useTexture(char* texDir, bool wrap) { FIBITMAP* imagePtr = FreeImage_ConvertTo32Bits( FreeImage_Load( FreeImage_GetFileType(texDir, 0), texDir) ); GLuint texture; glGenTextures(1, &texture); // i used to be 1 glBindTexture(GL_TEXTURE_2D, texture); glTexImage2D(GL_TEXTURE_2D, 0, GL_SRGB_ALPHA, FreeImage_GetWidth(imagePtr), FreeImage_GetHeight(imagePtr), 0, GL_BGRA, GL_UNSIGNED_BYTE, (void*)FreeImage_GetBits(imagePtr)); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, wrap ? GL_REPEAT : GL_CLAMP); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, wrap ? GL_REPEAT : GL_CLAMP); // Clear from RAM FreeImage_Unload(imagePtr); // Unbind when finished uplloading glBindTexture(GL_TEXTURE_2D, 0); return texture; }
/** Custom gamma correction based on the ITU-R BT.709 standard @param dib RGBF image to be corrected @param gammaval Gamma value (2.2 is a good default value) @return Returns TRUE if successful, returns FALSE otherwise */ static BOOL REC709GammaCorrection(FIBITMAP *dib, const float gammaval) { if(FreeImage_GetImageType(dib) != FIT_RGBF) return FALSE; float slope = 4.5F; float start = 0.018F; const float fgamma = (float)((0.45 / gammaval) * 2); if(gammaval >= 2.1F) { start = (float)(0.018 / ((gammaval - 2) * 7.5)); slope = (float)(4.5 * ((gammaval - 2) * 7.5)); } else if (gammaval <= 1.9F) { start = (float)(0.018 * ((2 - gammaval) * 7.5)); slope = (float)(4.5 / ((2 - gammaval) * 7.5)); } const unsigned width = FreeImage_GetWidth(dib); const unsigned height = FreeImage_GetHeight(dib); const unsigned pitch = FreeImage_GetPitch(dib); BYTE *bits = (BYTE*)FreeImage_GetBits(dib); for(unsigned y = 0; y < height; y++) { float *pixel = (float*)bits; for(unsigned x = 0; x < width; x++) { for(int i = 0; i < 3; i++) { *pixel = (*pixel <= start) ? *pixel * slope : (1.099F * pow(*pixel, fgamma) - 0.099F); pixel++; } } bits += pitch; } return TRUE; }
// CPreview message handlers void CPreview::OnPaint() { CPaintDC dc(this); // device context for painting CRect rct; GetClientRect(&rct); dc.FillSolidRect(&rct, m_clr); // Fill background first if (m_dib != NULL) { // Draw the thumbnail int width = (int)(FreeImage_GetWidth(m_dib)*theApp.thumb_zoom_); if (width > rct.Width()) width = rct.Width(); int height = (int)(FreeImage_GetHeight(m_dib)*theApp.thumb_zoom_); if (height > rct.Height()) height = rct.Height(); int left = (rct.Width() - width)/2; if (left < 0) left = 0; ::StretchDIBits(dc.GetSafeHdc(), left, 0, width, height, 0, 0, FreeImage_GetWidth(m_dib), FreeImage_GetHeight(m_dib), FreeImage_GetBits(m_dib), FreeImage_GetInfo(m_dib), DIB_RGB_COLORS, SRCCOPY); } else { // Just draw some text to say there is no preview dc.SetTextAlign(TA_CENTER); dc.TextOut(rct.Width()/2, 20, "No Preview ", 12); dc.TextOut(rct.Width()/2, 40, "Available ", 12); } }
static void TestFIA_IOLoadColourArrayData(CuTest* tc) { FIBITMAP *dib1 = NULL, *dib2 = NULL; FREE_IMAGE_TYPE type; int bpp, err; const char *file = "C:\\cup.tif"; dib1 = FIA_LoadFIBFromFile(file); CuAssertTrue(tc, dib1 != NULL); dib2 = FreeImage_AllocateT (FIT_BITMAP, FreeImage_GetWidth(dib1), FreeImage_GetHeight(dib1), 8, 0, 0, 0); PROFILE_START("CopyColourBytesToFIBitmap"); for(int i=0; i < 1000; i++) { //FIA_CopyColourBytesToFIBitmap (dib2, FreeImage_GetBits(dib1), 0, 1, COLOUR_ORDER_RGB); FIA_CopyColourBytesTo8BitFIBitmap (dib2, FreeImage_GetBits(dib1), 24, FI_RGBA_RED, 0, 1); } PROFILE_STOP("CopyColourBytesToFIBitmap"); FIA_SaveFIBToFile (dib2, TEST_DATA_OUTPUT_DIR "/IO/save-colour-test.bmp", BIT8); FreeImage_Unload(dib1); FreeImage_Unload(dib2); }
/** * Applies a scale to the height and width specified as paramteres. Returns 0 if there is no image loaded, or if the scaling fails (wrong bitdepth or to large image memorywise). * * * TODO: It could be nice to add an extra parameter so that a user could choose to use our "default" filter choice, or to specify what exact filter there is to be used. * * possible filter choices by FreeImage: * * Filter flag, Description * FILTER_BOX Box, pulse, Fourier window, 1st order (constant) B-Spline * FILTER_BILINEAR Bilinear filter * FILTER_BSPLINE 4th order (cubic) B-Spline * FILTER_BICUBIC Mitchell and Netravali's two-param cubic filter * FILTER_CATMULLROM Catmull-Rom spline, Overhauser spline * FILTER_LANCZOS3 Lanczos-windowed sinc filter * * @param pWidth Width in píxels. * @param pHeight Height in píxels. */ bool IND_Image::scale(int pWidth, int pHeight) { // No image loaded if (!isImageLoaded()) return false; FIBITMAP *scaled = NULL; // Scaling filter (when minimizing => Bilinear | when maximizing => Catmull-Rom) if (pWidth < getWidth() || pHeight < getHeight()) scaled = FreeImage_Rescale(getFreeImageHandle(), pWidth, pHeight, FILTER_BILINEAR); else scaled = FreeImage_Rescale(getFreeImageHandle(), pWidth, pHeight, FILTER_CATMULLROM); // scaling can in some rare circumstances return a NULL value (NULL value is returned when the bitdepth cannot be handled or when there is not enough memory (very large images)). if (scaled == NULL) return false; //Reset image parameters to new freeimage modified one FreeImage_Unload(getFreeImageHandle()); setFreeImageHandle(scaled); setPointer(FreeImage_GetBits(scaled)); setWidth(FreeImage_GetWidth(getFreeImageHandle())); setHeight(FreeImage_GetHeight(getFreeImageHandle())); return true; }
/** * Converts the image to the specified format. * First convert to requested different color format, then convert to the requested bit depth. * Returns false if there is no image loaded or conversion is not possible. * @param pColorFormat Format of the image. See ::IND_ColorFormat. * @param pBpp New bits per pixel of the image. */ bool IND_Image::convert(IND_ColorFormat pColorFormat, int pBpp) { // No image loaded if (!isImageLoaded()) return false; //First convert based in target color format (if needed) FIBITMAP* converted; converted = FreeImageHelper::convertColorFormat(getFreeImageHandle(),pColorFormat); if (converted &&converted != getFreeImageHandle()) { FreeImage_Unload(getFreeImageHandle()); setFreeImageHandle(converted); } //Convert based in bpp (if needed) converted = FreeImageHelper::convertBpp(getFreeImageHandle(),pBpp); if (converted && converted != getFreeImageHandle()) { FreeImage_Unload(getFreeImageHandle()); setFreeImageHandle(converted); } //Reset image parameters to new freeimage modified one if (converted) { setFreeImageHandle(converted); IND_ColorFormat indFormat = FreeImageHelper::calculateINDFormat(converted); setFormatInt(indFormat); setBpp(FreeImage_GetBPP(converted)); setBytespp(FreeImage_GetBPP(converted)/8); setPointer(FreeImage_GetBits(converted)); } return converted != NULL; }
GLuint load_texture(char* file, GLint param) { BYTE* bits(0); unsigned int width(0), height(0); GLuint gl_texID; FIBITMAP *dib = get_dib(file); if (!dib) return -1; bits = FreeImage_GetBits(dib); width = FreeImage_GetWidth(dib); height = FreeImage_GetHeight(dib); if ((bits == 0) || (width == 0) || (height == 0)) return -1; glGenTextures(1, &gl_texID); glBindTexture(GL_TEXTURE_2D, gl_texID); if (FreeImage_GetBPP(dib) == 24){ glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, width, height, 0, GL_BGR, GL_UNSIGNED_BYTE, bits); } else if (FreeImage_GetBPP(dib) == 32){ glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, width, height, 0, GL_BGRA, GL_UNSIGNED_BYTE, bits); } glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, param); glBindTexture(GL_TEXTURE_2D,0); FreeImage_Unload(dib); return gl_texID; }
/* * \brief Method that import a texture to be used on the model * \param[in] fTexture a constant char array containing the path to the file of the texture * \param[in] tex_number an unsigned integer representing the type of texture (i.e. 0 = Diffuse color, 1 = Normalmap, 2 = Specular Color) * \return a boolean indicating if the import was successful of not */ GLboolean Model::importTexture(const GLchar * fTexture, GLuint tex_number) { GLboolean import_is_ok = GL_FALSE; FREE_IMAGE_FORMAT fif = FIF_UNKNOWN; FIBITMAP *dib(0); BYTE* bits(0); GLuint width(0), height(0); fif = FreeImage_GetFileType(fTexture, 0); if (FreeImage_FIFSupportsReading(fif)) { dib = FreeImage_Load(fif, fTexture); dib = FreeImage_ConvertTo32Bits(dib); bits = FreeImage_GetBits(dib); width = FreeImage_GetWidth(dib); height = FreeImage_GetHeight(dib); import_is_ok = GL_TRUE; glBindTexture(GL_TEXTURE_2D, m_texture_id[tex_number]); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, width, height, 0, GL_BGRA, GL_UNSIGNED_BYTE, &bits[0]); glGenerateMipmap(GL_TEXTURE_2D); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR_MIPMAP_LINEAR); FreeImage_Unload(dib); } return import_is_ok; }
/////////////////////////////////////////////////////////////////////////// /// /// @fn bool glLoadTexture(const std::string& nomFichier, unsigned int& idTexture, /// bool genererTexture) /// /// Cette fonction crée une texture OpenGL à partir d'une image contenu /// dans un fichier. FreeImage est utilisée pour lire l'image, donc tous /// les formats reconnues par cette librairie devraient être supportés. /// /// @param[in] nomFichier : Le nom du fichier image à charger. /// @param[out] idTexture : L'identificateur de la texture créée. /// @param[in] genererTexture : Doit-on demander à OpenGL de générer un numéro /// de texture au préalable? /// /// @return Vrai si le chargement a réussi, faux autrement. /// /////////////////////////////////////////////////////////////////////////// bool glLoadTexture(const std::string& nomFichier, unsigned int& idTexture, bool genererTexture) { // Ce code de lecture générique d'un fichier provient de la // documentation de FreeImage FREE_IMAGE_FORMAT format = FIF_UNKNOWN; // check the file signature and deduce its format // (the second argument is currently not used by FreeImage) format = FreeImage_GetFileType(nomFichier.c_str(), 0); if(format == FIF_UNKNOWN) { // no signature ? // try to guess the file format from the file extension format = FreeImage_GetFIFFromFilename(nomFichier.c_str()); } // check that the plugin has reading capabilities ... if((format == FIF_UNKNOWN) || !FreeImage_FIFSupportsReading(format)) { utilitaire::afficherErreur( std::string("Format du fichier image \"") + std::string(nomFichier.c_str()) + std::string("\" non supporté") ); return false; } // ok, let's load the file FIBITMAP* dib = FreeImage_Load(format, nomFichier.c_str(), 0); if (dib == 0) { utilitaire::afficherErreur( std::string("Erreur à la lecture du fichier \"") + std::string(nomFichier.c_str()) + std::string("\"") ); return false; } FIBITMAP* dib32 = FreeImage_ConvertTo32Bits(dib); if (dib32 == 0) { utilitaire::afficherErreur( std::string("Incapable de convertir le fichier \"") + std::string(nomFichier.c_str()) + std::string("\" en 32 bpp.") ); FreeImage_Unload(dib); return false; } int pitch = FreeImage_GetPitch(dib32); glCreateTexture( FreeImage_GetBits(dib32), FreeImage_GetWidth(dib32), FreeImage_GetHeight(dib32), FreeImage_GetBPP(dib32), FreeImage_GetPitch(dib32), idTexture, genererTexture ); FreeImage_Unload(dib32); FreeImage_Unload(dib); return true; }
unsigned char * HVSTGFX::loadImageFile(char *fileName, HVSTGFX::IMAGEFILE * imgFile, GLuint &texture) { //FREE_IMAGE_FORMAT fif = FIF_PNG; FREE_IMAGE_FORMAT fif = FreeImage_GetFIFFromFilename(fileName); //pointer to the image data unsigned char* bits; unsigned char tempRGB; GLuint tempTex = 0; GLenum errCode; const unsigned char *errString; bool error = false; std::string file(fileName); if(FreeImage_FIFSupportsReading(fif)) imgFile->dib = FreeImage_Load(fif, fileName); if(!imgFile->dib) { glbl->debugger->writeString("failed to open sprite " + *fileName); return NULL; } bits = FreeImage_GetBits(imgFile->dib); imgFile->width = FreeImage_GetWidth(imgFile->dib); imgFile->height = FreeImage_GetHeight(imgFile->dib); imgFile->size = sizeof(bits); int size = imgFile->width*imgFile->height;//(FreeImage_GetWidth(dib) * FreeImage_GetHeight(dib)); for (int imageIDx = 0; imageIDx < size * 4; imageIDx += 4) { tempRGB = bits[imageIDx]; bits[imageIDx] = bits[imageIDx + 2]; bits[imageIDx + 2] = tempRGB; } glGenTextures(1, &tempTex); texture = tempTex; errCode = glGetError(); if (errCode != GL_NO_ERROR) { MessageBox(NULL, _T("Unable to detect OpenGL support. Check if you have your graphics driver installed, or if your graphics card supports OpenGL."), NULL, NULL); } glBindTexture(GL_TEXTURE_2D, texture); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, imgFile->width, imgFile->height, 0, GL_RGBA, GL_UNSIGNED_BYTE, bits); //FreeImage_Unload(dib); #ifdef _DEBUG if (!error) glbl->debugger->writeString("successfully loaded sprite " + file + "\n"); #endif return bits; }
FREEIMAGE_BMP* FREEIMAGE_LoadImage(const UString& filePath) { FREEIMAGE_BMP* vix_bmp = new FREEIMAGE_BMP; vix_bmp->path = filePath; vix_bmp->name = getFileName(filePath); vix_bmp->format = FREEIMAGE_FormatFromExtension(getFileExtension(filePath, false)); vix_bmp->data = NULL; vix_bmp->bitmap = NULL; /*Here we must */ //Check file signature and deduce format #ifdef UNICODE vix_bmp->format = FreeImage_GetFileTypeU(filePath.c_str()); #else vix_bmp->format = FreeImage_GetFileType(filePath.c_str()); #endif if (vix_bmp->format == FIF_UNKNOWN) { #ifdef UNICODE vix_bmp->format = FreeImage_GetFIFFromFilenameU(filePath.c_str()); #else vix_bmp->format = FreeImage_GetFIFFromFilename(filePath.c_str()); #endif } //if still unknown, return NULL; if (vix_bmp->format == FIF_UNKNOWN) return NULL; //Check if FreeImage has reading capabilities if (FreeImage_FIFSupportsReading(vix_bmp->format)) { #ifdef UNICODE //read image into struct pointer vix_bmp->bitmap = FreeImage_LoadU(vix_bmp->format, filePath.c_str()); #else vix_bmp->bitmap = FreeImage_Load(vix_bmp->format, filePath.c_str()); #endif } //If image failed to load, return NULL if (!vix_bmp->bitmap) return NULL; FreeImage_FlipVertical(vix_bmp->bitmap); //Retrieve image data vix_bmp->data = FreeImage_GetBits(vix_bmp->bitmap); //Retrieve image width vix_bmp->header.width = FreeImage_GetWidth(vix_bmp->bitmap); //Retrieve image height vix_bmp->header.height = FreeImage_GetHeight(vix_bmp->bitmap); if (vix_bmp->data == 0 || vix_bmp->header.width == 0 || vix_bmp->header.height == 0) return NULL; //return bitmap return vix_bmp; }
/** Coarse-to-fine prolongation by bilinear interpolation. nf is the fine-grid dimension. The coarsegrid solution is input as uc[0..nc-1][0..nc-1], where nc = nf/2 + 1. The fine-grid solution is returned in uf[0..nf-1][0..nf-1]. */ static void fmg_prolongate(FIBITMAP *UF, FIBITMAP *UC, int nf) { int row_uc, row_uf, col_uc, col_uf; const int uf_pitch = FreeImage_GetPitch(UF) / sizeof(float); const int uc_pitch = FreeImage_GetPitch(UC) / sizeof(float); float *uf_bits = (float*)FreeImage_GetBits(UF); const float *uc_bits = (float*)FreeImage_GetBits(UC); // do elements that are copies { const int nc = nf/2 + 1; float *uf_scan = uf_bits; const float *uc_scan = uc_bits; for (row_uc = 0; row_uc < nc; row_uc++) { for (col_uc = 0, col_uf = 0; col_uc < nc; col_uc++, col_uf += 2) { // calculate UF(2*row_uc, col_uf) = UC(row_uc, col_uc); uf_scan[col_uf] = uc_scan[col_uc]; } uc_scan += uc_pitch; uf_scan += 2 * uf_pitch; } } // do odd-numbered columns, interpolating vertically { for(row_uf = 1; row_uf < nf-1; row_uf += 2) { float *uf_scan = uf_bits + row_uf * uf_pitch; for (col_uf = 0; col_uf < nf; col_uf += 2) { // calculate UF(row_uf, col_uf) = 0.5 * ( UF(row_uf+1, col_uf) + UF(row_uf-1, col_uf) ) uf_scan[col_uf] = 0.5F * ( *(uf_scan + uf_pitch + col_uf) + *(uf_scan - uf_pitch + col_uf) ); } } } // do even-numbered columns, interpolating horizontally { float *uf_scan = uf_bits; for(row_uf = 0; row_uf < nf; row_uf++) { for (col_uf = 1; col_uf < nf-1; col_uf += 2) { // calculate UF(row_uf, col_uf) = 0.5 * ( UF(row_uf, col_uf+1) + UF(row_uf, col_uf-1) ) uf_scan[col_uf] = 0.5F * ( uf_scan[col_uf + 1] + uf_scan[col_uf - 1] ); } uf_scan += uf_pitch; } } }
bool tpImageIO::readHDR(tpImageColorHDR& I, const char* path) { FREE_IMAGE_FORMAT fifmt = FreeImage_GetFileType(path, 0); if(fifmt == FIF_UNKNOWN) { std::cerr << "[Error] tpImageIO : Unknow type !" << std::endl; //TODO: Exceptions ? return false; } FIBITMAP *dib = FreeImage_Load(fifmt, path,0); if( dib == NULL ) { std::cerr << "[Error] tpImageIO : Impossible d'ouvrir l'image : " << path << std::endl; // TODO: Exceptions ? return false; } if(FreeImage_GetImageType(dib)!=FIT_RGBF) { std::cerr << "[Error] tpImageIO : Unknow type !" << std::endl; //TODO: Exceptions ? return false; } unsigned width = FreeImage_GetWidth(dib); unsigned height = FreeImage_GetHeight(dib); unsigned pitch = FreeImage_GetPitch(dib); I.resize(height,width); FREE_IMAGE_TYPE image_type = FreeImage_GetImageType(dib); // test pixel access avoiding scanline calculations // to speed-up the image processing if(image_type == FIT_RGBF) { BYTE *bits = (BYTE*)FreeImage_GetBits(dib); for(int y = 0; y < height; y++) { FIRGBF *pixel = (FIRGBF*)bits; for(int x = 0; x < width; x++) { I[y][x].r = pixel[x].red; I[y][x].g = pixel[x].green; I[y][x].b = pixel[x].blue; } // next line bits += pitch; } } FreeImage_Unload(dib); return true; }
SDL_Surface *GraphicsHelps::fi2sdl(FIBITMAP *img) { int h = static_cast<int>(FreeImage_GetHeight(img)); int w = static_cast<int>(FreeImage_GetWidth(img)); FreeImage_FlipVertical(img); SDL_Surface *surf = SDL_CreateRGBSurfaceFrom(FreeImage_GetBits(img), w, h, 32, w * 4, FI_RGBA_RED_MASK, FI_RGBA_GREEN_MASK, FI_RGBA_BLUE_MASK, FI_RGBA_ALPHA_MASK); return surf; }
/** Does coarse-to-fine interpolation and adds result to uf. nf is the fine-grid dimension. The coarse-grid solution is input as uc[0..nc-1][0..nc-1], where nc = nf/2+1. The fine-grid solution is returned in uf[0..nf-1][0..nf-1]. res[0..nf-1][0..nf-1] is used for temporary storage. */ static void fmg_addint(FIBITMAP *UF, FIBITMAP *UC, FIBITMAP *RES, int nf) { fmg_prolongate(RES, UC, nf); const int uf_pitch = FreeImage_GetPitch(UF) / sizeof(float); const int res_pitch = FreeImage_GetPitch(RES) / sizeof(float); float *uf_bits = (float*)FreeImage_GetBits(UF); const float *res_bits = (float*)FreeImage_GetBits(RES); for(int row = 0; row < nf; row++) { for(int col = 0; col < nf; col++) { // calculate UF(row, col) = UF(row, col) + RES(row, col); uf_bits[col] += res_bits[col]; } uf_bits += uf_pitch; res_bits += res_pitch; } }
unsigned char* GLES2Texture::loadImage(const char *filename, int& colorDepth) { //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(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 NULL; //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) return NULL; int datasize = FreeImage_GetDIBSize(dib); //retrieve the image data bits = FreeImage_GetBits(dib); //get the image width and height width = FreeImage_GetWidth(dib); height = FreeImage_GetHeight(dib); //get the image bpp colorDepth = FreeImage_GetBPP(dib); //if this somehow one of these failed (they shouldn't), return failure if((bits == 0) || (width == 0) || (height == 0)) return NULL; mWidth = width; mHeight = height; // BGRA 转成 RGBA unsigned char* buffer = new unsigned char[datasize]; int i=0; for (i=0; i<datasize; i+=4) { (buffer+i)[0] = (bits+i)[2]; (buffer+i)[1] = (bits+i)[1]; (buffer+i)[2] = (bits+i)[0]; (buffer+i)[3] = (bits+i)[3]; } //Free FreeImage's copy of the data FreeImage_Unload(dib); return buffer; }
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; }
CMImage::CMImage(char* name) : Resource(name) { FREE_IMAGE_FORMAT formato = FreeImage_GetFIFFromFilename(name); FIBITMAP* imagen = FreeImage_Load(formato, name); _name = name; _width = FreeImage_GetWidth(imagen); _height = FreeImage_GetHeight(imagen); void* pixeles = (void*)FreeImage_GetBits(imagen); FREE_IMAGE_TYPE a = FreeImage_GetImageType(imagen); assert(a == FIT_BITMAP); unsigned int bitDepth= FreeImage_GetBPP(imagen); assert(bitDepth == 24 || bitDepth == 32 || bitDepth == 48); _pixelData = pixeles; switch (bitDepth) { case 24: _imageFormat = GL_BGR; break; case 32: _imageFormat = GL_BGRA; break; case 48: _imageFormat = GL_BGRA; break; } glGenTextures(1, &_textureId);//generates texture glBindTexture(GL_TEXTURE_2D, _textureId); glTexImage2D( GL_TEXTURE_2D, 0, 4, _width, _height, 0, _imageFormat, GL_UNSIGNED_BYTE, FreeImage_GetBits(imagen) ); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glBindTexture(GL_TEXTURE_2D, 0u); FreeImage_Unload(imagen); }
/* Loads a texture froma file to be applied to the terrain @param the path to the texture file @return whether or not the file was loaded correctly */ bool Ground::loadGroundTexture(string path) { FREE_IMAGE_FORMAT fif = FIF_UNKNOWN; FIBITMAP* texture(0); fif = FreeImage_GetFileType(path.c_str(), 0); if (fif == FIF_UNKNOWN) { // Unknown file type //std::cout << "Unknown Filetype\n"; fif = FreeImage_GetFIFFromFilename(path.c_str()); } if (fif == FIF_UNKNOWN) { // Still unkown file type std::cout << "Unknown Filetype\n"; return false; } if (FreeImage_FIFSupportsReading(fif)) { // is the file supported by free image? texture = FreeImage_Load(fif, path.c_str()); } if (!texture) { std::cout << "This file type is not supported by FreeImage\n"; return false; } BYTE* dataPointer = FreeImage_GetBits(texture); textureWidth = FreeImage_GetWidth(texture); textureHeight = FreeImage_GetHeight(texture); textureBPP = FreeImage_GetBPP(texture); glGenTextures(1, &textureID); glBindTexture(GL_TEXTURE_2D, textureID); int format = textureBPP == 24 ? GL_BGR : textureBPP == 8 ? GL_LUMINANCE : 0; int internalFormat = textureBPP == 24 ? GL_BGR : GL_DEPTH_COMPONENT; glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, textureWidth, textureHeight, 0, format, GL_UNSIGNED_BYTE, dataPointer); glGenerateMipmap(GL_TEXTURE_2D); FreeImage_Unload(texture); glGenSamplers(1, &samplerID); texturePath = path; // Tri linear filtering 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); glGenerateMipmap(GL_TEXTURE_2D); return true; }
bool CTexture::Load(const char* texPath){ //if we already load texture, you have to delete previous... if (TextureId != NULL) glDeleteTextures(1, &TextureId); FREE_IMAGE_FORMAT format = FreeImage_GetFileType(texPath, 0); FIBITMAP* image = FreeImage_Load(format, texPath); if (format == FIF_UNKNOWN){ std::cout << "unknown texture format: file " << texPath << std::endl; return false; }; FIBITMAP* temp = image; image = FreeImage_ConvertTo32Bits(image); FreeImage_Unload(temp); int w = FreeImage_GetWidth(image); int h = FreeImage_GetHeight(image); char* bits = (char*)FreeImage_GetBits(image); // OpenGL stuff /* TODO: Texture settings */ glGenTextures(1, &TextureId); glBindTexture(GL_TEXTURE_2D, TextureId); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, w, h, 0, GL_BGRA, GL_UNSIGNED_BYTE, (GLvoid*)bits); /* Generate Mipmap */ glGenerateMipmap(GL_TEXTURE); //glGenerateTextureMipmapEXT(TextureId); //glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); //glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST_MIPMAP_NEAREST); //glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST_MIPMAP_NEAREST); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); GLfloat fLargest; glGetFloatv(GL_MAX_TEXTURE_MAX_ANISOTROPY_EXT, &fLargest); //glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAX_ANISOTROPY_EXT, fLargest); GLenum Error = glGetError(); if (Error){ std::cerr << "There was an error loading the texture" << std::endl; return false; } return true; }
void putBmpIntoPixels(FIBITMAP * bmp, ofPixels_<PixelType> &pix, bool swapForLittleEndian = true) { // convert to correct type depending on type of input bmp and PixelType FIBITMAP* bmpConverted = NULL; FREE_IMAGE_TYPE imgType = FreeImage_GetImageType(bmp); if(sizeof(PixelType)==1 && (FreeImage_GetColorType(bmp) == FIC_PALETTE || FreeImage_GetBPP(bmp) < 8 || imgType!=FIT_BITMAP)) { if(FreeImage_IsTransparent(bmp)) { bmpConverted = FreeImage_ConvertTo32Bits(bmp); } else { bmpConverted = FreeImage_ConvertTo24Bits(bmp); } bmp = bmpConverted; }else if(sizeof(PixelType)==2 && imgType!=FIT_UINT16 && imgType!=FIT_RGB16 && imgType!=FIT_RGBA16){ if(FreeImage_IsTransparent(bmp)) { bmpConverted = FreeImage_ConvertToType(bmp,FIT_RGBA16); } else { bmpConverted = FreeImage_ConvertToType(bmp,FIT_RGB16); } bmp = bmpConverted; }else if(sizeof(PixelType)==4 && imgType!=FIT_FLOAT && imgType!=FIT_RGBF && imgType!=FIT_RGBAF){ if(FreeImage_IsTransparent(bmp)) { bmpConverted = FreeImage_ConvertToType(bmp,FIT_RGBAF); } else { bmpConverted = FreeImage_ConvertToType(bmp,FIT_RGBF); } bmp = bmpConverted; } unsigned int width = FreeImage_GetWidth(bmp); unsigned int height = FreeImage_GetHeight(bmp); unsigned int bpp = FreeImage_GetBPP(bmp); unsigned int channels = (bpp / sizeof(PixelType)) / 8; unsigned int pitch = FreeImage_GetPitch(bmp); // ofPixels are top left, FIBITMAP is bottom left FreeImage_FlipVertical(bmp); unsigned char* bmpBits = FreeImage_GetBits(bmp); if(bmpBits != NULL) { pix.setFromAlignedPixels((PixelType*) bmpBits, width, height, channels, pitch); } else { ofLogError("ofImage") << "putBmpIntoPixels(): unable to set ofPixels from FIBITMAP"; } if(bmpConverted != NULL) { FreeImage_Unload(bmpConverted); } #ifdef TARGET_LITTLE_ENDIAN if(swapForLittleEndian && sizeof(PixelType) == 1) { pix.swapRgb(); } #endif }