unsigned char pixel_intensity[] to image; C code, Linux

和自甴很熟 提交于 2019-12-13 09:28:55

问题


I have a data array of pixel intensity (e.g. unsigned char pixel_intensity[4] = {0, 255, 255, 0}) and I need to create image in C code on Linux (Raspberry Pi).

What is the easiest way to do it?


回答1:


I would suggest using the netpbm format as it is very easy to program. It is documented here and here.

I have written a little demonstration of how to write a simple greyscale ramp to a 100x256 image below.

#include <stdio.h>
#include <stdlib.h>

int main(){

   FILE *imageFile;
   int x,y,pixel,height=100,width=256;

   imageFile=fopen("image.pgm","wb");
   if(imageFile==NULL){
      perror("ERROR: Cannot open output file");
      exit(EXIT_FAILURE);
   }

   fprintf(imageFile,"P5\n");           // P5 filetype
   fprintf(imageFile,"%d %d\n",width,height);   // dimensions
   fprintf(imageFile,"255\n");          // Max pixel

   /* Now write a greyscale ramp */
   for(x=0;x<height;x++){
      for(y=0;y<width;y++){
         pixel=y;
         fputc(pixel,imageFile);
      }
   }

   fclose(imageFile);
}

The header of the image looks like this:

P5
256 100
255
<binary data of pixels>

And the image looks like this (I have made it into a JPEG for rendering on here)

Once you have an image, you can use the superb ImageMagick (here) tools to convert the image to anything else you like, e.g. if you want the greyscale created by the above converted into a JPEG, just use ImageMagick like this:

convert image.pgm image.jpg

Or, if you want a PNG

convert image.pgm image.png

You can actually use the PGM format images directly on the web, by convention, the MIME type is image/x-portable-graymap



来源:https://stackoverflow.com/questions/22364686/unsigned-char-pixel-intensity-to-image-c-code-linux

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!