Image* FW::importLodePngImage(InputStream& stream) { // Read the entire input stream. Array<U8> dataBuffer; int blockSize = 4096; for (;;) { int pos = dataBuffer.getSize(); dataBuffer.resize(pos + blockSize); int num = stream.read(dataBuffer.getPtr(pos), blockSize); if (num < blockSize) { dataBuffer.resize(pos + num); break; } } if (hasError()) return NULL; // Decode image info. LodePNG::Decoder decoder; decoder.inspect(dataBuffer.getPtr(), dataBuffer.getSize()); Vec2i size(decoder.getWidth(), decoder.getHeight()); bool hasAlpha = (LodePNG_InfoColor_canHaveAlpha(&decoder.getInfoPng().color) != 0); if (decoder.hasError()) setError("importLodePngImage(): LodePNG error %d!", decoder.getError()); if (min(size) <= 0) setError("importLodePngImage(): Invalid image size!"); if (hasError()) return NULL; // Decode image data. int numBytes = size.x * size.y * ((hasAlpha) ? 4 : 3); std::vector<U8> pixelBuffer; pixelBuffer.reserve(numBytes); decoder.getInfoRaw().color.colorType = (hasAlpha) ? 6 : 2; decoder.decode(pixelBuffer, dataBuffer.getPtr(), dataBuffer.getSize()); if (decoder.hasError()) setError("importLodePngImage(): LodePNG error %d!", decoder.getError()); if ((int)pixelBuffer.size() != numBytes) setError("importLodePngImage(): Incorrect amount of pixel data!"); if (hasError()) return NULL; // Create image. Image* image = new Image(size, (hasAlpha) ? ImageFormat::R8_G8_B8_A8 : ImageFormat::R8_G8_B8); image->getBuffer().set(&pixelBuffer[0], numBytes); return image; }
// Load image from file [true = success, false otherwise] bool PNG::load(string pathname){ std::vector<unsigned char> buffer; LodePNG::loadFile(buffer, pathname); //load the image file with given filename LodePNG::Decoder decoder; decoder.inspect(buffer); if (decoder.isGreyscaleType()){ decoder.getInfoRaw().color.colorType = 0; decoder.getInfoRaw().color.bitDepth = 16; // is grayscale } decoder.decode(image, buffer); width = decoder.getWidth(); height = decoder.getHeight(); if(decoder.hasError()) { return false; } return true; }