Create an RGBA image in C++ -
i have matrix of 640x480x4 values, i.e. 640x480 pixels each 4 channels (rgba). want create png file shows transparency. have tried using opencv, apparently transparency not supported. quickest , easiest way can this, need save few images?
as other said, can't write png image file in c++ without using external library.
libpng
smallest , portable solution, official png reference library , used of image library write , read png files. it's easy use c library may not best solution c++ novice.
exemple of writing png image libpng
:
file *fp = fopen("file.png", "wb"); png_structp png_ptr = png_create_write_struct(png_libpng_ver_string, 0, 0, 0); png_infop info_ptr = png_create_info_struct(png_ptr); png_init_io(png_ptr, fp); /* write header */ png_set_ihdr(png_ptr, info_ptr, width, height, bit_depth, color_type, png_interlace_none, png_compression_type_base, png_filter_type_base); png_write_info(png_ptr, info_ptr); /* write bytes */ png_bytep * row_pointers; <allocate row_pointers , store each row of image in it> png_write_image(png_ptr, row_pointers); png_write_end(png_ptr, null); /* cleanup heap allocation */ (y=0; y<height; y++) free(row_pointers[y]); free(row_pointers); fclose(fp);
as can see needs quite lines initialize writing context, , voluntarily removed error management bit tricky libpng
(use of setjmp
instance) , definitly not suitable novice c programmer.
you may take @ higher level image library such imagemagick
has c++ api called magick++
, here example of writing image in memory png file :
magick::blob blob(data, length); magick::image image; image.size("640x480") image.magick("rgba"); image.read(blob); image.write("file.png");
as can see, it's easier higher level library.