void Texture::loadImageFromMemory(const unsigned char* blob, unsigned int size, bool flipOnLoad) { unsigned char* pixels = nullptr; int width, height, comp; // stbi_load_from_memory loads the image as a serie of scanline starting from // the top-left corner of the image. When shouldFlip is set to true, the image // would be flipped vertically. stbi_set_flip_vertically_on_load((int)flipOnLoad); if (blob != nullptr && size != 0) { pixels = stbi_load_from_memory(blob, size, &width, &height, &comp, STBI_rgb_alpha); } if (pixels) { resize(width, height); setData(reinterpret_cast<GLuint*>(pixels), width * height); stbi_image_free(pixels); m_validData = true; } else { // Default inconsistent texture data is set to a 1*1 pixel texture // This reduces inconsistent behavior when texture failed loading // texture data but a Tangram style shader requires a shader sampler GLuint blackPixel = 0x0000ff; setData(&blackPixel, 1); LOGE("Decoding image from memory failed"); m_validData = false; } }
void Stb::Read(SoyPixelsImpl& Pixels,const ArrayBridge<char>& ArrayBuffer,TReadFunction ReadFunction) { #if defined(USE_STB) const stbi_uc* Buffer = reinterpret_cast<const stbi_uc*>( ArrayBuffer.GetArray() ); auto BufferSize = size_cast<int>( ArrayBuffer.GetDataSize() ); int Width = 0; int Height = 0; int Channels = 0; int RequestedChannels = 4; auto* DecodedPixels = stbi_load_from_memory( Buffer, BufferSize, &Width, &Height, &Channels, RequestedChannels ); if ( !DecodedPixels ) { // gr: as this is not thread safe, it could come out mangled :( maybe add a lock around error popping before read (maybe have to lock around the whole thing) auto* StbError = stbi_failure_reason(); if ( !StbError ) StbError = "Unknown error"; std::stringstream Error; Error << "Failed to read image pixels; " << StbError; throw Soy::AssertException( Error.str() ); } // convert output into pixels // gr: have to assume size auto Format = SoyPixelsFormat::GetFormatFromChannelCount( Channels ); SoyPixelsMeta Meta( Width, Height, Format ); SoyPixelsRemote OutputPixels( DecodedPixels, Meta.GetDataSize(), Meta ); Pixels.Copy( OutputPixels ); #else throw Soy::AssertException("No STB support, no image reading"); #endif }
static bool create_ios_launch_images(const char *dir, export_config *conf) { size_t len; stbi_uc *img_data; int width, height; if (conf->launch_image == NULL) { width = 1024; height = 1024; len = width * height * 4; img_data = (stbi_uc*)malloc(len); memset(img_data, 255, len); } else { void *data = am_read_file(conf->launch_image, &len); int components = 4; stbi_set_flip_vertically_on_load(0); img_data = stbi_load_from_memory((stbi_uc const *)data, len, &width, &height, &components, 4); free(data); if (img_data == NULL) return false; } if (!resize_image(img_data, width, height, dir, "Default.png", 320, 480) || !resize_image(img_data, width, height, dir, "*****@*****.**", 640, 960) || !resize_image(img_data, width, height, dir, "*****@*****.**", 640, 1136) || !resize_image(img_data, width, height, dir, "*****@*****.**", 750, 1334) || !resize_image(img_data, width, height, dir, "*****@*****.**", 1242, 2208) || !resize_image(img_data, width, height, dir, "Default-Landscape@2x~ipad.png", 2048, 1536) || !resize_image(img_data, width, height, dir, "Default-Landscape~ipad.png", 1024, 768) || !resize_image(img_data, width, height, dir, "Default-Portrait@2x~ipad.png", 1536, 2048) || !resize_image(img_data, width, height, dir, "Default-Portrait~ipad.png", 768, 1024) ) return false; free(img_data); return true; }
// Inherited via Task virtual void run() override { LOG_SCOPE_TIME(BitEngine::EngineLog, "Texture load"); ResourceLoader::DataRequest dr(nullptr); if (textureData) { dr = std::move(textureData->getData()); } else { dr = std::move(useData); } if (dr.isLoaded()) { texture->imgData.fileData.swap(dr.data); texture->imgData.pixelData = stbi_load_from_memory((unsigned char*)texture->imgData.fileData.data(), texture->imgData.fileData.size(), &texture->imgData.width, &texture->imgData.height, &texture->imgData.color, 0); if (texture->imgData.pixelData != nullptr) { LOG(BitEngine::EngineLog, BE_LOG_VERBOSE) << "stbi loaded texture: " << dr.meta->getNameId() << " w: " << texture->imgData.width << " h: " << texture->imgData.height; manager->uploadToGPU(texture); } else { LOG(BitEngine::EngineLog, BE_LOG_ERROR) << "stbi failed to load texture: " << dr.meta->getNameId() << " reason: " << stbi_failure_reason(); } } else { LOG(BitEngine::EngineLog, BE_LOG_ERROR) << "Resource meta " << dr.meta->getNameId() << " on state: " << dr.loadState; } }
int ImageLoad(Image *i, const unsigned char *data, size_t size) { if (!i) { X2(bad_arg, "NULL image pointer"); } if (!data) { X2(bad_arg, "NULL data pointer"); } if (size == 0) { X2(bad_arg, "size must be non-zero"); } if (size > INT_MAX) { X2(bad_size, "stb_image cannot load more than INT_MAX bytes in any one image"); } unsigned char *uc; int x, y, comp; uc = stbi_load_from_memory(data, (int) size, &x, &y, &comp, RGBA_CHANNELS); if (!uc) { X(stbi_load_from_memory); } i->size = Size2D((size_t) x, (size_t) y); i->elements = i->size.x * i->size.y; i->bytes = i->elements * RGBA_SIZE; i->pixels = uc; return 1; err_stbi_load_from_memory: err_bad_size: err_bad_arg: return 0; }
uint8 *image_decode_other(uint8 *content,int32 bytes,int32 *result,int32 *x,int32 *y){ //Result:bit 1=Success,bit 2=32bit[BGRA] *result=0; int32 h=0,w=0; uint8 *out; int comp=0; out=stbi_load_from_memory(content,bytes,&w,&h,&comp,4); if (out==NULL) return NULL; if (comp!=4) return NULL; //RGBA->BGRA uint8* cp=out; int32 x2,y2; int32 r,g,b,a; for (y2=0;y2<h;y2++){ for (x2=0;x2<w;x2++){ r=cp[0]; b=cp[2]; cp[0]=b; cp[2]=r; cp+=4; } } *result=1+2; *x=w; *y=h; return out; }
TextureCube loadTextureCubeFromFolder(Platform *platform, RenderContext *render_context, std::string folder_name) { u8 *images[6]; char *names[] = { "right", "left", "top", "bottom", "front", "back", }; int tex_w, tex_h, tex_comps; for(int i = 0; i < 6; i++) { std::string path = "data/textures/skyboxes/" + folder_name + "/" + std::string(names[i]) + ".jpg"; FileData file = platform->readEntireFile(path.c_str()); u8 *texture_data = stbi_load_from_memory((stbi_uc *)file.contents, file.size, &tex_w, &tex_h, &tex_comps, 4); images[i] = texture_data; } TextureCube result = render_context->createTextureCube(images, tex_w, tex_h, RenderContext::Format::u32_unorm); for(int i = 0; i < 6; i++) { stbi_image_free(images[i]); } return result; }
RenderImageCairo::RenderImageCairo(void* data, size_t len) { int x, y, n; stbi_buffer_ = stbi_load_from_memory((const stbi_uc*)data, len, &x, &y, &n, 4); Color* pColorBegin = (Color*)stbi_buffer_; for (int i = 0; i < x*y; i++) { Color* pColor = pColorBegin + i; Color origin = *pColor; uint8 a = ColorGetA(origin); uint8 r = ColorGetB(origin); uint8 g = ColorGetG(origin); uint8 b = ColorGetR(origin); if (a < 255) { *pColor = ColorSetARGB(a, r*a/255, g*a/255, b*a/255); } else { *pColor = ColorSetARGB(a, r, g, b); } } size_.SetSize(x, y); cairo_format_t format = CAIRO_FORMAT_ARGB32; int stride = cairo_format_stride_for_width(format, x); image_surface_ = cairo_image_surface_create_for_data(stbi_buffer_, format, x, y, stride); }
static int load_image(lua_State *L) { am_check_nargs(L, 1); char *errmsg; int len; const char *filename = luaL_checkstring(L, 1); void *data = am_read_resource(filename, &len, &errmsg); if (data == NULL) { lua_pushstring(L, errmsg); free(errmsg); return lua_error(L); } int width, height; int components = 4; stbi_set_flip_vertically_on_load(1); stbi_uc *img_data = stbi_load_from_memory((stbi_uc const *)data, len, &width, &height, &components, 4); free(data); if (img_data == NULL) { return luaL_error(L, "error loading image %s: %s", filename, stbi_failure_reason()); } am_image_buffer *img = am_new_userdata(L, am_image_buffer); img->width = width; img->height = height; img->format = AM_PIXEL_FORMAT_RGBA8; int sz = width * height * pixel_format_size(img->format); am_buffer *imgbuf = am_new_userdata(L, am_buffer); imgbuf->size = sz; imgbuf->data = img_data; img->buffer = imgbuf; img->buffer_ref = img->ref(L, -1); lua_pop(L, 1); // pop imgbuf return 1; }
Result loadRgba8888TextureFromAsset(const char *pPath, vector<uint8_t> *pBuffer, unsigned *pWidth, unsigned *pHeight) { vector<uint8_t> compressed; if (FAILED(OS::getAssetManager().readBinaryFile(&compressed, pPath))) { LOGE("Failed to read texture: %s.\n", pPath); return RESULT_ERROR_IO; } int x, y, comp; uint8_t *pResult = stbi_load_from_memory(compressed.data(), compressed.size(), &x, &y, &comp, STBI_rgb_alpha); if (!pResult || comp != STBI_rgb_alpha) { LOGE("Failed to decompress texture: %s.\n", pPath); free(pResult); return RESULT_ERROR_GENERIC; } pBuffer->clear(); pBuffer->insert(end(*pBuffer), pResult, pResult + x * y * 4); *pWidth = x; *pHeight = y; free(pResult); return RESULT_SUCCESS; }
void ae3d::Texture2D::LoadSTB( const FileSystem::FileContentsData& fileContents ) { int components; unsigned char* data = stbi_load_from_memory( &fileContents.data[ 0 ], static_cast<int>(fileContents.data.size()), &width, &height, &components, 4 ); if (data == nullptr) { const std::string reason( stbi_failure_reason() ); System::Print( "%s failed to load. stb_image's reason: %s\n", fileContents.path.c_str(), reason.c_str() ); return; } opaque = (components == 3 || components == 1); if (GfxDevice::HasExtension("GL_ARB_texture_storage")) { glTexStorage2D( GL_TEXTURE_2D, 1, GL_RGBA8, width, height ); glTexSubImage2D( GL_TEXTURE_2D, 0, 0, 0, width, height, GL_RGBA, GL_UNSIGNED_BYTE, data ); } else { glTexImage2D( GL_TEXTURE_2D, 0, GL_RGBA, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, data ); } stbi_image_free( data ); }
GLuint render_create_texture(const char* filename) { GLuint texture; int width; int height; int comp; void* data; glGenTextures(1, &texture); glBindTexture(GL_TEXTURE_2D, texture); glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MIN_FILTER,GL_LINEAR); glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MAG_FILTER,GL_LINEAR); #ifdef ANDROID char* file_data = NULL; int file_size = 0; system_load_file_to_memory( filename, &file_data, &file_size ); data = stbi_load_from_memory( (unsigned char*)file_data, file_size, &width, &height, &comp, 4 ); #else data = stbi_load(system_get_path(filename), &width, &height, &comp, 4); #endif if(data == NULL) { CNSLog("Texture %s load failed", filename); return 0; } glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, data); glGenerateMipmap(GL_TEXTURE_2D); stbi_image_free(data); glBindTexture(GL_TEXTURE_2D, 0); return texture; }
void initProgram(std::vector<char> &buf) { gProgram = createProgram(gVertexShader, gFragmentShader); unsigned char* pixels ; int w, h, bpp; pixels = stbi_load_from_memory((const unsigned char *)&buf[0], buf.size(), &w, &h, &bpp, 4); LOGD("s:%d-%d(%d)", w, h, bpp); GLuint texName = 0; glGenTextures(1, &texName); if (!texName) { LOGE("** ERROR (create texture) **"); exit(1); } glBindTexture(GL_TEXTURE_2D, texName); 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_MAG_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR); glPixelStorei(GL_UNPACK_ALIGNMENT, 1); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, w, h, 0, GL_RGBA, GL_UNSIGNED_BYTE, pixels); glGenerateMipmap(GL_TEXTURE_2D); }
unsigned char * imageLoadFromMemory( const void * _data, size_t _size, uint32_t & _width, uint32_t & _height ) { int wi_frame; int he_frame; int n; unsigned char * pixels = stbi_load_from_memory( (const stbi_uc *)_data, (int)_size, &wi_frame, &he_frame, &n, 4 ); for( int i = 0; i != wi_frame; ++i ) { for( int j = 0; j != he_frame; ++j ) { int index = i + j * wi_frame; unsigned char r = pixels[index * 4 + 0]; pixels[index * 4 + 0] = pixels[index * 4 + 2]; pixels[index * 4 + 2] = r; } } _width = wi_frame; _height = he_frame; return pixels; }
void *loom_asset_imageDeserializer( void *buffer, size_t bufferLen, LoomAssetCleanupCallback *dtor ) { loom_asset_image_t *img; lmAssert(buffer != NULL, "buffer should not be null"); img = (loom_asset_image_t*)lmAlloc(gAssetAllocator, sizeof(loom_asset_image_t)); // parse any orientation info from exif format img->orientation = exifinfo_parse_orientation(buffer, (unsigned int)bufferLen); img->bits = stbi_load_from_memory((const stbi_uc *)buffer, (int)bufferLen, &img->width, &img->height, &img->bpp, 4); *dtor = loom_asset_imageDtor; if(!img->bits) { lmLogError(gImageAssetGroup, "Image load failed due to this cryptic reason: %s", stbi_failure_reason()); lmFree(gAssetAllocator, img); return 0; } lmLogDebug(gImageAssetGroup, "Allocated %d bytes for an image!", img->width * img->height * 4); return img; }
bool Image::LoadFromFile(const std::string& filePath) { m_pixels.clear(); int width, height, depth; FileManager fr(filePath); BINARY_DATA data = fr.ReadBinary(); BYTE* pointer = stbi_load_from_memory(static_cast<stbi_uc*>(data.ptr()), data.size(), &width, &height, &depth, NULL); data.clear(); if (pointer && width && height) { m_size.x = static_cast<float>(width); m_size.y = static_cast<float>(height); m_depth = static_cast<BYTE>(depth); m_pixels.resize(width * height * depth); // Flip the pixels horizontally into OpenGL format. for (int i = 0; i < height; ++i) { std::memcpy(&m_pixels[i * width * depth], &pointer[m_pixels.size() - (i * width * depth) - width * depth], width * depth); } stbi_image_free(pointer); } else { return false; } m_loaded = true; return true; }
static int load_embedded_image(lua_State *L) { am_check_nargs(L, 1); const char *filename = luaL_checkstring(L, 1); am_embedded_file_record *rec = am_get_embedded_file(filename); if (rec == NULL) { return luaL_error(L, "embedded file not found: %s", filename); } int width, height; int components = 4; stbi_set_flip_vertically_on_load(1); stbi_uc *img_data = stbi_load_from_memory((stbi_uc const *)rec->data, rec->len, &width, &height, &components, 4); if (img_data == NULL) { return luaL_error(L, "error loading image %s: %s", filename, stbi_failure_reason()); } am_image_buffer *img = am_new_userdata(L, am_image_buffer); img->width = width; img->height = height; img->format = AM_PIXEL_FORMAT_RGBA8; int sz = width * height * pixel_format_size(img->format); am_buffer *imgbuf = am_new_userdata(L, am_buffer); imgbuf->size = sz; imgbuf->data = img_data; img->buffer = imgbuf; img->buffer_ref = img->ref(L, -1); lua_pop(L, 1); // pop imgbuf return 1; }
void Texture::LoadImgDataFromFileData() { // Load the file pixels into memory // RGBA in byte order bool should_load = false; { MutexLock lock( m_Mutex ); should_load = ( m_ImgFileData != NULL ) && ( m_ImgFileDataSize > 0 ); } if( should_load ) { int width, height, channels; unsigned char* img_data = stbi_load_from_memory( reinterpret_cast< const unsigned char* >( m_ImgFileData ), m_ImgFileDataSize, &width, &height, &channels, 4 ); { MutexLock lock( m_Mutex ); m_Width = width; m_Height = height; m_ImgData = img_data; } } }
void cImage::LoadFromPack( cPack * Pack, const std::string& FilePackPath ) { if ( NULL != Pack && Pack->IsOpen() && -1 != Pack->Exists( FilePackPath ) ) { SafeDataPointer PData; Pack->ExtractFileToMemory( FilePackPath, PData ); int w, h, c; Uint8 * data = stbi_load_from_memory( PData.Data, PData.DataSize, &w, &h, &c, mChannels ); if ( NULL != data ) { mPixels = data; mWidth = (eeUint)w; mHeight = (eeUint)h; if ( STBI_default == mChannels ) mChannels = (eeUint)c; mSize = mWidth * mHeight * mChannels; mLoadedFromStbi = true; } else { eePRINTL( "Failed to load image %s. Reason: %s", stbi_failure_reason(), FilePackPath.c_str() ); } } else { eePRINTL( "Failed to load image %s from pack.", FilePackPath.c_str() ); } }
int cellPngDecDecodeData(u32 mainHandle, u32 subHandle, mem8_ptr_t data, const mem_struct_ptr_t<CellPngDecDataCtrlParam> dataCtrlParam, mem_struct_ptr_t<CellPngDecDataOutInfo> dataOutInfo) { dataOutInfo->status = CELL_PNGDEC_DEC_STATUS_STOP; ID sub_handle_id_data; if(!cellPngDec.CheckId(subHandle, sub_handle_id_data)) return CELL_PNGDEC_ERROR_FATAL; auto subHandle_data = (CellPngDecSubHandle*)sub_handle_id_data.m_data; const u32& fd = subHandle_data->fd; const u64& fileSize = subHandle_data->fileSize; const CellPngDecOutParam& current_outParam = subHandle_data->outParam; //Copy the PNG file to a buffer MemoryAllocator<unsigned char> png(fileSize); MemoryAllocator<u64> pos, nread; cellFsLseek(fd, 0, CELL_SEEK_SET, pos); cellFsRead(fd, png.GetAddr(), png.GetSize(), nread); //Decode PNG file. (TODO: Is there any faster alternative? Can we do it without external libraries?) int width, height, actual_components; std::shared_ptr<unsigned char> image(stbi_load_from_memory(png, fileSize, &width, &height, &actual_components, 4)); if (!image) return CELL_PNGDEC_ERROR_STREAM_FORMAT; uint image_size = width * height; switch(current_outParam.outputColorSpace) { case CELL_PNGDEC_RGB: case CELL_PNGDEC_RGBA: image_size *= current_outParam.outputColorSpace == CELL_PNGDEC_RGBA ? 4 : 3; memcpy(data, image.get(), image_size); break; case CELL_PNGDEC_ARGB: image_size *= 4; for(uint i = 0; i < image_size; i+=4) { data += image.get()[i+3]; data += image.get()[i+0]; data += image.get()[i+1]; data += image.get()[i+2]; } break; case CELL_PNGDEC_GRAYSCALE: case CELL_PNGDEC_PALETTE: case CELL_PNGDEC_GRAYSCALE_ALPHA: cellPngDec.Error("cellPngDecDecodeData: Unsupported color space (%d)", current_outParam.outputColorSpace.ToLE()); break; default: return CELL_PNGDEC_ERROR_ARG; } dataOutInfo->status = CELL_PNGDEC_DEC_STATUS_FINISH; return CELL_OK; }
unsigned char* Image::GetImageData(Deserializer& source, int& width, int& height, unsigned& components) { unsigned dataSize = source.GetSize(); SharedArrayPtr<unsigned char> buffer(new unsigned char[dataSize]); source.Read(buffer.Get(), dataSize); return stbi_load_from_memory(buffer.Get(), dataSize, &width, &height, (int *)&components, 0); }
int cellGifDecDecodeData(u32 mainHandle, u32 subHandle, mem8_ptr_t data, const mem_ptr_t<CellGifDecDataCtrlParam> dataCtrlParam, mem_ptr_t<CellGifDecDataOutInfo> dataOutInfo) { if (!data.IsGood() || !dataCtrlParam.IsGood() || !dataOutInfo.IsGood()) return CELL_GIFDEC_ERROR_ARG; dataOutInfo->status = CELL_GIFDEC_DEC_STATUS_STOP; CellGifDecSubHandle* subHandle_data; if(!cellGifDec->CheckId(subHandle, subHandle_data)) return CELL_GIFDEC_ERROR_FATAL; const u32& fd = subHandle_data->fd; const u64& fileSize = subHandle_data->fileSize; const CellGifDecOutParam& current_outParam = subHandle_data->outParam; //Copy the GIF file to a buffer MemoryAllocator<unsigned char> gif(fileSize); MemoryAllocator<u64> pos, nread; cellFsLseek(fd, 0, CELL_SEEK_SET, pos); cellFsRead(fd, gif.GetAddr(), gif.GetSize(), nread); //Decode GIF file. (TODO: Is there any faster alternative? Can we do it without external libraries?) int width, height, actual_components; std::shared_ptr<unsigned char> image(stbi_load_from_memory(gif, fileSize, &width, &height, &actual_components, 4)); if (!image) return CELL_GIFDEC_ERROR_STREAM_FORMAT; uint image_size = width * height * 4; switch((u32)current_outParam.outputColorSpace) { case CELL_GIFDEC_RGBA: if (!Memory.CopyFromReal(data.GetAddr(), image.get(), image_size)) { cellGifDec->Error("cellGifDecDecodeData() failed (dataa_addr=0x%x)", data.GetAddr()); return CELL_EFAULT; } break; case CELL_GIFDEC_ARGB: for(uint i = 0; i < image_size; i+=4) { data += image.get()[i+3]; data += image.get()[i+0]; data += image.get()[i+1]; data += image.get()[i+2]; } break; default: return CELL_GIFDEC_ERROR_ARG; } dataOutInfo->status = CELL_GIFDEC_DEC_STATUS_FINISH; dataOutInfo->recordType = CELL_GIFDEC_RECORD_TYPE_IMAGE_DESC; return CELL_OK; }
inline unsigned char * load_png_image(FSFile & image_file, int size, int * w, int * h, int * channels) { unsigned char * buf = new unsigned char[size]; image_file.read(buf, size); unsigned char * out = stbi_load_from_memory(buf, size, w, h, channels, 4); delete[] buf; return out; }
bool LoadImageData(Image *image, const int image_idx, std::string *err, std::string *warn, int req_width, int req_height, const unsigned char *bytes, int size, void *) { (void)warn; const int requiredComponents = 4; int w, h, comp; unsigned char *data = stbi_load_from_memory(bytes, size, &w, &h, &comp, requiredComponents); if (!data) { // NOTE: you can use `warn` instead of `err` if (err) { (*err) += "Unknown image format.\n"; } return false; } if (w < 1 || h < 1) { free(data); if (err) { (*err) += "Invalid image data.\n"; } return false; } if (req_width > 0) { if (req_width != w) { free(data); if (err) { (*err) += "Image width mismatch.\n"; } return false; } } if (req_height > 0) { if (req_height != h) { free(data); if (err) { (*err) += "Image height mismatch.\n"; } return false; } } image->width = w; image->height = h; image->component = requiredComponents; image->image.resize(static_cast<size_t>(w * h * image->component)); std::copy(data, data + w * h * image->component, image->image.begin()); free(data); return true; }
//--------------------------------------------------------------------- Codec::DecodeResult STBIImageCodec::decode(DataStreamPtr& input) const { // Buffer stream into memory (TODO: override IO functions instead?) MemoryDataStream memStream(input, true); int width, height, components; stbi_uc* pixelData = stbi_load_from_memory(memStream.getPtr(), static_cast<int>(memStream.size()), &width, &height, &components, 0); if (!pixelData) { OGRE_EXCEPT(Exception::ERR_INTERNAL_ERROR, "Error decoding image: " + String(stbi_failure_reason()), "STBIImageCodec::decode"); } SharedPtr<ImageData> imgData(OGRE_NEW ImageData()); MemoryDataStreamPtr output; imgData->depth = 1; // only 2D formats handled by this codec imgData->width = width; imgData->height = height; imgData->num_mipmaps = 0; // no mipmaps in non-DDS imgData->flags = 0; switch( components ) { case 1: imgData->format = PF_BYTE_L; break; case 2: imgData->format = PF_BYTE_LA; break; case 3: imgData->format = PF_BYTE_RGB; break; case 4: imgData->format = PF_BYTE_RGBA; break; default: stbi_image_free(pixelData); OGRE_EXCEPT(Exception::ERR_ITEM_NOT_FOUND, "Unknown or unsupported image format", "STBIImageCodec::decode"); break; } size_t dstPitch = imgData->width * PixelUtil::getNumElemBytes(imgData->format); imgData->size = dstPitch * imgData->height; output.bind(OGRE_NEW MemoryDataStream(pixelData, imgData->size, true)); DecodeResult ret; ret.first = output; ret.second = imgData; return ret; }
Waifu2x::eWaifu2xError Waifu2x::LoadMatBySTBI(cv::Mat &float_image, const std::vector<char> &img_data) { int x, y, comp; stbi_uc *data = stbi_load_from_memory((const stbi_uc *)img_data.data(), img_data.size(), &x, &y, &comp, 4); if (!data) return eWaifu2xError_FailedOpenInputFile; int type = 0; switch (comp) { case 1: case 3: case 4: type = CV_MAKETYPE(CV_8U, comp); break; default: return eWaifu2xError_FailedOpenInputFile; } float_image = cv::Mat(cv::Size(x, y), type); const auto LinePixel = float_image.step1() / float_image.channels(); const auto Channel = float_image.channels(); const auto Width = float_image.size().width; const auto Height = float_image.size().height; assert(x == Width); assert(y == Height); assert(Channel == comp); auto ptr = float_image.data; for (int i = 0; i < y; i++) { for (int j = 0; j < x; j++) { for (int ch = 0; ch < Channel; ch++) ptr[(i * LinePixel + j) * comp + ch] = data[(i * x + j) * comp + ch]; } } stbi_image_free(data); if (comp >= 3) { // RGBだからBGRに変換 for (int i = 0; i < y; i++) { for (int j = 0; j < x; j++) std::swap(ptr[(i * LinePixel + j) * comp + 0], ptr[(i * LinePixel + j) * comp + 2]); } } return eWaifu2xError_OK; }
int RegistTexMem( unsigned char *ptr, int size ) { // メモリ上の画像ファイルデータからテクスチャ読み込み // (TEXINFのidを返す) // GLuint id; int texid, tsx,tsy,comp; int sx,sy; unsigned char *pImg; unsigned char *pImg2; pImg = stbi_load_from_memory( ptr, size, &tsx, &tsy, &comp, 4 ); id = -1; if ( pImg != NULL ) { sx = Get2N( tsx ); sy = Get2N( tsy ); if (( sx != tsx )||( sy != tsy )) { // Exchange to 2N bitmap char *p; char *p2; int x,y; pImg2 = (unsigned char *)mem_ini( sx * sy * 4 ); p = (char *)pImg; p2 = (char *)pImg2; for(y=0;y<tsy;y++) { #if 0 p2 = (char *)pImg2 + (sx*y*4); for(x=0;x<tsx;x++) { p2[0] = p[0]; p2[1] = p[1]; p2[2] = p[2]; p2[3] = p[3]; p+=4; p2+=4; } #else memcpy( p2, p, tsx*4 ); p+=tsx*4; p2+=sx*4; #endif } mem_bye(pImg); pImg = pImg2; } glGenTextures( 1, &id ); glBindTexture( GL_TEXTURE_2D, id ); glTexImage2D( GL_TEXTURE_2D, 0, GL_RGBA, sx, sy, 0, GL_RGBA, GL_UNSIGNED_BYTE, pImg ); mem_bye(pImg); texid = SetTex( -1, TEXMODE_NORMAL, 0, sx, sy, tsx, tsy, id ); Alertf( "Tex:ID%d (%d,%d)(%dx%d)",texid,sx,sy,tsx,tsy ); return texid; } Alertf( "Tex:failed" ); return -1; }
void DBTexture::writeCompressedToRaw() { int w = m_width, h = m_height, n = m_numComp; byte* data = stbi_load_from_memory(m_compressedData.data(), int(m_compressedData.size_bytes()), &w, &h, &n, m_numComp); assert(w == m_width && h == m_height && n == m_numComp); uint dataSize = m_width * m_height * m_numComp * m_pixColSize; m_rawData.resize(dataSize); memcpy(m_rawData.data(), data, dataSize); stbi_image_free(data); }
unsigned char *ImageLoader::loadRawDataFromMemory(const void *data, int len, int *w, int *h, int *comp, int req_comp) { const unsigned char* buffer = static_cast<const unsigned char*>(data); unsigned char* texdata = 0; #ifdef DQBIX_USE_STB_IMAGE texdata = stbi_load_from_memory(buffer, len, w, h, comp, req_comp); #else texdata = SOIL_load_image_from_memory(buffer, len, w, h, comp, req_comp); #endif return texdata; }
std::unique_ptr<HeightData> downloadHeightmapTile(const std::string& url, const Tile& tile, float extrusionScale) { std::stringstream out; if (downloadData(out, url)) { unsigned char* pixels; int width, height, comp; // Decode texture PNG const unsigned char* pngData = reinterpret_cast<const unsigned char*>(out.str().c_str()); pixels = stbi_load_from_memory(pngData, out.str().length(), &width, &height, &comp, STBI_rgb_alpha); // printf("Texture data %d width, %d height, %d comp\n", width, height, comp); if (comp != STBI_rgb_alpha) { printf("Failed to decompress PNG file\n"); return nullptr; } std::unique_ptr<HeightData> data = std::unique_ptr<HeightData>(new HeightData()); data->elevation.resize(height); for (int i = 0; i < height; ++i) { data->elevation[i].resize(width); } data->width = width; data->height = height; unsigned char* pixel = pixels; for (size_t i = 0; i < width * height; i++, pixel += 4) { float red = *(pixel+0); float green = *(pixel+1); float blue = *(pixel+2); // Decode the elevation packed data from color component float elevation = (red * 256 + green + blue / 256) - 32768; int y = i / height; int x = i % width; assert(x >= 0 && x <= width && y >= 0 && y <= height); data->elevation[x][y] = elevation * extrusionScale; } return data; } return nullptr; }