LibPng Read Into Struct - c++

I cannot seem to get libpng to dump its data into my struct. I can't figure out what I'm doing wrong. I'm trying to flip the bytes because PNG's are stored top->down and I need the data bottom->up.
First my struct looks like:
typedef union RGB
{
uint32_t Color;
struct
{
unsigned char B, G, R, A;
} RGBA;
} *PRGB;
Then I created a vector as such:
png_init_io(PngPointer, hFile);
png_set_sig_bytes(PngPointer, 8);
png_read_info(PngPointer, InfoPointer);
uint32_t width, height;
int bitdepth, colortype, interlacetype, channels;
png_set_strip_16(PngPointer);
channels = png_get_channels(PngPointer, InfoPointer);
png_get_IHDR(PngPointer, InfoPointer, &width, &height, &bitdepth, &colortype, &interlacetype, nullptr, nullptr);
uint32_t RowBytes = png_get_rowbytes(PngPointer, InfoPointer);
unsigned char** RowPointers = png_get_rows(PngPointer, InfoPointer);
std::vector<RGB> Pixels(RowBytes * height); //Amount of bytes in one row * height of image.
//Crashes in the for loop below :S
for (int I = 0; I < height; I++)
{
for (int J = 0; J < width; J++)
{
Pixels[(height - 1 - I) * width + J].RGBA.B = *(RowPointers[J]++);
Pixels[(height - 1 - I) * width + J].RGBA.G = *(RowPointers[J]++);
Pixels[(height - 1 - I) * width + J].RGBA.R = *(RowPointers[J]++);
}
}
std::fclose(hFile);
png_destroy_read_struct(&PngPointer, &InfoPointer, nullptr);
What did I do wrong? How can I get the pixels of the PNG and store them upside down? I used the same technique for bitmaps but PNG just isn't working :l

Shouldn't this:
Pixels[(height - 1 - I) * width + J].RGBA.B = *(RowPointers[J]++);
Index RowPointers via I instead?

Related

Problems with BMP

Wrote a simple BMP generation code but instead of outputting what I want (red that gradually goes to black (from left to right)) it returns an image with some some weird layout far from what I expect to see. Was inspecting the way header and pixels written in the memory and everything seems alright
Output
#include <iostream>
#include <fstream>
size_t width = 1000, height = 1000, CPP = 3;
//this creates an array of pixels
//supposed to be from red to black from left to right
uint8_t* createBitMapI(const size_t& width, const size_t& height)
{
uint8_t _color[3] = { 255, 0, 0 };
uint8_t* bitMap = new uint8_t[width * height * 3];
//creating one row
for (float i = 0; i < width; i++)
{
*(bitMap + (int)(i * 3)) = (uint8_t)_color[0] * (1 - i / width);
*(bitMap + 1 + (int)(i * 3)) = 0;//(uint8_t)_color[1] * (1 - i / width);
*(bitMap + 2 + (int)(i * 3)) = 0;//(uint8_t)_color[2] * (1 - i / width);
}
//copying previously created row to others
for (size_t i = 1; i < height; i++)
{
memcpy(bitMap + (width * 3) * i, bitMap, width * 3);
}
return bitMap;
}
//creates BMP file and writes contents into it
class BMP
{
public:
BMP(const size_t& width, const size_t& height,
uint8_t* arr, const char* name)
{
const char pad_[3] = { 0, 0, 0 };
char padding = (4 - width % 4) % 4;
fullSize = (width + padding) * height * 3 + 54;
image.open(name);
writeHeader();
image.write((const char*)header, 54);
for (size_t i = 0; i < height; i++)
{
image.write((const char*)arr + (i * width), width * 3);
image.write(pad_, padding);
}
image.close();
}
void writeHeader()
{
memcpy(header, "BM", 2);
*(size_t*)(header + 2) = fullSize;
*(size_t*)(header + 10) = 54;
*(size_t*)(header + 14) = 40;
*(size_t*)(header + 18) = width;
*(size_t*)(header + 22) = height;
*(uint16_t*)(header + 26) = 1;
*(uint16_t*)(header + 28) = 24;
}
private:
std::ofstream image;
uint8_t header[54];
uint8_t* pixels;
size_t fullSize;
};
int main()
{
uint8_t* arr = createBitMapI(width, height);
BMP newImage(width, height, arr, "image.bmp");
delete[] arr;
}
upd: changing image.open(name) to image.open(name, std::ios::binary) gives us output2

How to correct horizontal flip function to prevent it from altering images' colors

stb_image.h provides a method to flip an image vertically and it works fine. I tried to implement an horizontal flip aka mirror but it alters the image colors.
On pictures that only have 3 colors you could get bluish or reddish or even magenta colored pictures instead of their actual colors. It's the same if we're talking about JPEG or PNG images, you get the same strange results. Curiously if you flip that very same image vertically, its colors look normal.
I've tried testing pretty much any function you could find here and the code I'm providing you with has been the only one that got me close to my actual goal.
// Function I've been trying to implement to enable Horizontal Flip
static void stbi_horizontal_flip(void *image, int w, int h, int bytes_per_pixel)
{
size_t line_bytes = (size_t)w * bytes_per_pixel;
stbi_uc temp[line_bytes];
stbi_uc *bytes = (stbi_uc *)image;
Debug() << line_bytes;
for (int col = 0; col < h; col++) {
stbi_uc *line = bytes + col * line_bytes;
memcpy(&temp, line, line_bytes);
for (int row = 0; row < line_bytes; row++) {
line[row] = temp[line_bytes - row - bytes_per_pixel];
}
}
stbi_horizontally_flip_on_load = false;
}
// stb_image's function for Vertical Flip
static void stbi__vertical_flip(void *image, int w, int h, int bytes_per_pixel)
{
int row;
size_t bytes_per_row = (size_t)w * bytes_per_pixel;
stbi_uc temp[2048];
stbi_uc *bytes = (stbi_uc *)image;
for (row = 0; row < (h>>1); row++) {
stbi_uc *row0 = bytes + row * bytes_per_row;
stbi_uc *row1 = bytes + (h - row - 1) * bytes_per_row;
size_t bytes_left = bytes_per_row;
while (bytes_left) {
size_t bytes_copy = (bytes_left < sizeof(temp)) ? bytes_left : sizeof(temp);
memcpy(temp, row0, bytes_copy);
memcpy(row0, row1, bytes_copy);
memcpy(row1, temp, bytes_copy);
row0 += bytes_copy;
row1 += bytes_copy;
bytes_left -= bytes_copy;
}
}
}
static unsigned char *stbi__load_and_postprocess_8bit(stbi__context *s, int *x, int *y, int *comp, int req_comp)
{
stbi__result_info ri;
void *result = stbi__load_main(s, x, y, comp, req_comp, &ri, 8);
if (result == NULL) return NULL;
if (ri.bits_per_channel != 8) {
STBI_ASSERT(ri.bits_per_channel == 16);
result = stbi__convert_16_to_8((stbi__uint16 *) result, *x, *y, req_comp == 0 ? *comp : req_comp);
ri.bits_per_channel = 8;
}
// #TODO: move stbi__convert_format to here
if (stbi_horizontally_flip_on_load) {
int channels = req_comp ? req_comp : *comp;
stbi_horizontal_flip(result, *x, *y, channels * sizeof(stbi_uc));
}
if (stbi__vertically_flip_on_load) {
int channels = req_comp ? req_comp : *comp;
stbi__vertical_flip(result, *x, *y, channels * sizeof(stbi_uc));
}
return (unsigned char *) result;
}
STBIDEF stbi_uc *stbi_load_from_file(FILE *f, int *x, int *y, int *comp, int req_comp)
{
unsigned char *result;
stbi__context s;
stbi__start_file(&s,f);
result = stbi__load_and_postprocess_8bit(&s,x,y,comp,req_comp);
if (result) {
// need to 'unget' all the characters in the IO buffer
fseek(f, - (int) (s.img_buffer_end - s.img_buffer), SEEK_CUR);
}
return result;
}
STBIDEF stbi_uc *stbi_load(char const *filename, int *x, int *y, int *comp, int req_comp)
{
FILE *f = stbi__fopen(filename, "rb");
unsigned char *result;
if (!f) return stbi__errpuc("can't fopen", "Unable to open file");
result = stbi_load_from_file(f,x,y,comp,req_comp);
fclose(f);
return result;
}
STBIDEF stbi_uc *stbi_load_from_callbacks(stbi_io_callbacks const *clbk, void *user, int *x, int *y, int *comp, int req_comp)
{
stbi__context s;
stbi__start_callbacks(&s, (stbi_io_callbacks *) clbk, user);
return stbi__load_and_postprocess_8bit(&s,x,y,comp,req_comp);
}
void Gosu::load_image_file(Gosu::Bitmap& bitmap, const string& filename)
{
Buffer buffer;
load_file(buffer, filename);
load_image_file(bitmap, buffer.front_reader());
}
void Gosu::load_image_file(Gosu::Bitmap& bitmap, Reader input)
{
bool needs_color_key = is_bmp(input);
stbi_io_callbacks callbacks;
callbacks.read = read_callback;
callbacks.skip = skip_callback;
callbacks.eof = eof_callback;
int x, y, n;
stbi_uc* bytes = stbi_load_from_callbacks(&callbacks, &input, &x, &y, &n, STBI_rgb_alpha);
if (bytes == nullptr) {
throw runtime_error("Cannot load image: " + string(stbi_failure_reason()));
}
bitmap.resize(x, y);
printf("Channels %d, Gosu Color size %d, unsigned char size %d, bytes array size %d",
n, sizeof(Gosu::Color), sizeof(stbi_uc), sizeof(bytes));
// Output: Channels 3 or 4, Gosu Color size 4, unsigned char size 1, bytes array 8
memcpy(bitmap.data(), bytes, x * y * sizeof(Gosu::Color));
stbi_image_free(bytes);
if (needs_color_key) apply_color_key(bitmap, Gosu::Color::FUCHSIA);
}```
// Output: Channels 3 or 4, Gosu Color size 4, unsigned char size 1, bytes array 8
That is what I got back from stb_image, but I'd prefer to get an 8bit array instead. Even so what actually matters is to get rid of that unexpected color change.
Thanks to Igor's comment I could focus on my immediate problem and not long after I came up with the code I've posted below.
What I've been wondering since I finally could flip the images horizontally was why the other methods I found either on the web or as part of image processors' code didn't work as expected. O_o? Sometimes I copied and pasted them only changing some variables' names or types to match stb_image's and they still failed either to compile or display a decent result.
By the way, I tried before to subtract positions to the right value to no avail but it made me think some of them could be used as nice color blend effects. XD
// Horizontal Flip by Kyonides Arkanthes shared under GPLv2 or v3
static void stbi_kyon_horizontal_flip(void *image, int w, int h, int bytes_per_pixel)
{
size_t line_bytes = (size_t)w * bytes_per_pixel;
stbi_uc temp[line_bytes];
stbi_uc *bytes = (stbi_uc *)image;
int lpos, rpos;
for (int col = 0; col < h; col++) {
stbi_uc *line = bytes + col * line_bytes;
memcpy(&temp, line, line_bytes);
for (int row = 0; row < w; row++) {
lpos = row * bytes_per_pixel;
rpos = line_bytes - row * bytes_per_pixel - 1;
line[lpos] = temp[rpos - 3];
line[lpos + 1] = temp[rpos - 2];
line[lpos + 2] = temp[rpos - 1];
line[lpos + 3] = temp[rpos];
}
}
stbi_kyon_horizontally_flip_on_load = false;
}```
You just reversed the order of RGBA, you try to use this, I tested, the effect is normal.
for (int row = 0; row < Qimg2.width(); row++) {
lpos = row * bytes_per_pixel;
rpos = line_bytes - row * bytes_per_pixel - 1;
line[lpos] = temp[rpos - 2];
line[lpos + 1] = temp[rpos - 1];
line[lpos + 2] = temp[rpos - 3];
line[lpos + 3] = temp[rpos];
}

Flip an image vertically

I'm trying to flip an image vertically, after retrieving the buffer from openGL. It seems to be outputting an incorrect image with the following code:
const int width = 100;
const int height = width;
const int components = 3;
unsigned char pixels[width * height * components];
glReadPixels(0, 0, width, height, GL_RGB, GL_UNSIGNED_BYTE, pixels);
unsigned char flipPixels[width * height * components];
for (int i = 0; i < width; ++i) {
for (int j = 0; j < height; ++j) {
for (int k = 0; k < components; ++k) {
flipPixels[i + j * width + k] = pixels[(height) * (width) - ((j+1) * width) + i + k];
}
}
}
I know I can only iterate half the height and achieve the same, but I want to implement it by going through the complete height of the image. I can't seem to figure out what's wrong with the code. Any help would be appreciated.
I'm not sure how the image is stored but your indices i and k are given the same stride which is suspicious. Maybe you want i * components and j * width * components. After that, inverting vertically you should only have to change j to (height - j - 1).
flipPixels[(i + j * width) * components + k] = pixels[(i + (height - 1 - j) * width) * components + k];
I had the same issue, the pixels returned by OpenGL resulten in an upside down bitmap. so I flipped them like this: but the bitmap is still flipped left to right...
void Flip(GLubyte* pixels, int pixelbuffersize)
{
// basically rewrites from bottom up...
std::vector<GLubyte> flipped_pixels(pixels, pixels+pixelbuffersize);
auto count = flipped_pixels.size();
std::reverse(flipped_pixels.begin(), flipped_pixels.end());
GLubyte* buff = (reinterpret_cast<GLubyte*>(&flipped_pixels[0]));
const void * pnewdata = (const void *)buff;
memcpy(pixels, pnewdata, count);
}

Simple Flip buffer (Vertically) issue in C\C++

I am trying to flip a buffer, but the buffer doesn't get fully processed.
Is a buffer of pixels and I need basically to flip it vertically.
Can anyone spot what am I doing wrong? Thanks in advance.
void flipVertically(unsigned int* buffer, const unsigned int width, const unsigned int height)
{
const unsigned int rowWidth = width; // Length of a row
const unsigned int rows = height / 2; // Iterate only half the buffer to get a full flip
unsigned int* tempRow = (unsigned int*)malloc(rowWidth);
for (int rowIndex = 0; rowIndex < rows; rowIndex++)
{
memcpy(tempRow, buffer + (rowIndex * rowWidth), rowWidth);
memcpy(buffer + (rowIndex * rowWidth), buffer + (height - rowIndex - 1) * rowWidth, rowWidth);
memcpy(buffer + (height - rowIndex - 1) * rowWidth, tempRow, rowWidth);
}
free(tempRow);
}
Will this work?
void flip(unsigned* buffer, unsigned width, unsigned height)
{
unsigned rows = height / 2; // Iterate only half the buffer to get a full flip
unsigned* tempRow = (unsigned*)malloc(width * sizeof(unsigned));
for (unsigned rowIndex = 0; rowIndex < rows; rowIndex++)
{
memcpy(tempRow, buffer + rowIndex * width, width * sizeof(unsigned));
memcpy(buffer + rowIndex * width, buffer + (height - rowIndex - 1) * width, width * sizeof(unsigned));
memcpy(buffer + (height - rowIndex - 1) * width, tempRow, width * sizeof(unsigned));
}
free(tempRow);
}

Bitmap 24 to 32 and back

This may be a long post but I really need to know how to Convert between 24 and 32 bit bitmaps. For the sake of the length of this post, I removed the PNG part of my question.
Here goes:
I have a struct like the one below that holds all pixel information:
typedef union RGB
{
uint32_t Color;
struct
{
unsigned char B, G, R, A;
} RGBA;
} *PRGB;
std::vector<RGB> Pixels; //Holds all pixels.
All of the bitmap writing works except when going from 24 to 32 or vice-versa. I don't know what I'm doing wrong or why 24-32 conversions don't work. My bitmap reading and writing code is as follows:
Bitmap(const void* Pointer, int Width, int Height, uint32_t BitsPerPixel) //Constructor initialization here...
{
Pixels.clear();
if (Pointer == nullptr) {throw std::logic_error("Null Pointer Exception. Pointer is NULL.");}
if (Width < 1 || Height < 1) {throw std::invalid_argument("Invalid Arguments. Width and Height cannot equal 0.");}
std::memset(&Info, 0, sizeof(BITMAPINFO));
size = ((width * BitsPerPixel + 31) / 32) * 4 * height;
Info.bmiHeader.biSize = sizeof(BITMAPINFOHEADER);
Info.bmiHeader.biWidth = width;
Info.bmiHeader.biHeight = height;
Info.bmiHeader.biPlanes = 1;
Info.bmiHeader.biBitCount = BitsPerPixel;
Info.bmiHeader.biCompression = BI_RGB;
Info.bmiHeader.biSizeImage = size;
bFileHeader.bfType = 0x4D42;
bFileHeader.bfOffBits = sizeof(BITMAPFILEHEADER) + sizeof(Info.bmiHeader);
bFileHeader.bfSize = bFileHeader.bfOffBits + size;
const unsigned char* BuffPos = static_cast<const unsigned char*>(Pointer);
height = (height < 0 ? -height : height);
Pixels.resize(width * height);
for (int I = 0; I < height; I++)
{
for (int J = 0; J < width; J++)
{
Pixels[(height - 1 - I) * width + J].RGBA.B = *(BuffPos++);
Pixels[(height - 1 - I) * width + J].RGBA.G = *(BuffPos++);
Pixels[(height - 1 - I) * width + J].RGBA.R = *(BuffPos++);
Pixels[(height - 1 - I) * width + J].RGBA.A = (Info.bmiHeader.biBitCount > 24 ? *(BuffPos++) : 0);
}
if(Info.bmiHeader.biBitCount == 24)
BuffPos += width % 4;
}
}
bool SaveBitmap(const char* FilePath)
{
std::vector<unsigned char> ImageData(size);
unsigned char* BuffPos = ImageData.data();
for (int I = 0; I < height; ++I)
{
for (int J = 0; J < width; ++J)
{
*(BuffPos++) = Pixels[(height - 1 - I) * width + J].RGBA.B;
*(BuffPos++) = Pixels[(height - 1 - I) * width + J].RGBA.G;
*(BuffPos++) = Pixels[(height - 1 - I) * width + J].RGBA.R;
if (Info.bmiHeader.biBitCount > 24)
*(BuffPos++) = Pixels[(height - 1 - I) * width + J].RGBA.A;
}
if(Info.bmiHeader.biBitCount == 24)
BuffPos += width % 4;
}
std::fstream hFile(FilePath, std::fstream::out | std::ofstream::binary);
if (!hFile.is_open()) return false;
hFile.write(reinterpret_cast<char*>(&bFileHeader), sizeof(BITMAPFILEHEADER));
hFile.write(reinterpret_cast<char*>(&Info.bmiHeader), sizeof (BITMAPINFOHEADER));
hFile.write(reinterpret_cast<char*>(&ImageData[0]), Size());
hFile.close();
return true;
}
Any idea what the two problems could be? I want it so that if I called Bitmap(24BmpBuff, W, H, 32); It'll save as 32. If I do Bitmap(32BmpBuff, W, H, 24) it'll save as 24 bit. I just can't see it so I'm hoping one of you will.
I also tried making helper functions:
Convert From 24 bit to 32 bit.
void T24To32(std::vector<RGB> &Input, std::vector<RGB> &Output, int Width, int Height)
{
Output.resize(Input.size());
for (int I = 0; I < Height; ++I)
{
for (int J = 0; J < Width; ++J)
{
Output[J].RGBA.B = Input[J].RGBA.B;
Output[J].RGBA.G = Input[J].RGBA.G;
Output[J].RGBA.R = Input[J].RGBA.R;
Output[J].RGBA.A = 0;
}
}
}
Take the unsigned char* of pixels and store them upside down within the struct.
void Pack(int width, int height, int BPP, unsigned char* Input, std::vector<RGB> &Pixels)
{
unsigned char* BuffPos = Input;
height = (height < 0 ? -height : height);
Pixels.resize(width * height);
for (int I = 0; I < height; I++)
{
for (int J = 0; J < width; J++)
{
Pixels[(height - 1 - I) * width + J].RGBA.B = *(BuffPos++);
Pixels[(height - 1 - I) * width + J].RGBA.G = *(BuffPos++);
Pixels[(height - 1 - I) * width + J].RGBA.R = *(BuffPos++);
Pixels[(height - 1 - I) * width + J].RGBA.A = (BPP > 24 ? *(BuffPos++) : 0);
}
if(BPP == 24)
BuffPos += width % 4;
}
}
Take the struct of pixels and store them upright in the unsigned char*.
void Unpack(int width, int height, int BPP, std::vector<RGB> Pixels, unsigned char* &Output)
{
unsigned char* BuffPos = Output;
for (int I = 0; I < height; ++I)
{
for (int J = 0; J < width; ++J)
{
*(BuffPos++) = Pixels[(height - 1 - I) * width + J].RGBA.B;
*(BuffPos++) = Pixels[(height - 1 - I) * width + J].RGBA.G;
*(BuffPos++) = Pixels[(height - 1 - I) * width + J].RGBA.R;
if (BPP > 24)
*(BuffPos++) = Pixels[(height - 1 - I) * width + J].RGBA.A;
}
if(BPP == 24)
BuffPos += width % 4;
}
}
I use all of the above like so.. Input image(32 bit):
Code:
void Bitmap32ToBitmap24(int Width, int Height)
{
Bitmap Image("C:/Images/Bitmap32.bmp");
std::vector<unsigned char> Pixels(((Width * 32 + 31) / 32) * 4 * Height); //Array large enough to hold 32 bit bmp.
unsigned char* BuffPos = Pixels.data();
Unpack(Width, Height, 32, Image.Get(), BuffPos); //Fill the array of unsigned char with image pixels being upright
Bitmap BMP(Pixels.data(), Width, Height, 24); //Convert image to 24 bit bmp and save it.
BMP.Save("C:/Images/Output/Bitmap32ToBitmap24.png");
}
Output image (24 bit):
24 to 32 results in:
In all your code snippets
if(Info.bmiHeader.biBitCount == 24)
BuffPos += width % 4;
or
if(BPP == 24)
BuffPos += width % 4;
occur. I assume this should add the padding value to each line. But it isn't the padding, it is the number of pixels per line %4.
The correct adding value is (4 - ((width * 3) % 4)) % 4. The width*3 is the number of bytes in that line. The %4 calculates the number of bytes which are to many for a 4 byte padding, but to fill up to the next higher limes we need 4-this value. This again is 4 if no padding offset is needed -> %4 to avoid that.
A faster way to compute the same value is (-width * 3) & 3. See wiki.