Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
448 views
in Technique[技术] by (71.8m points)

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

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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
");           // P5 filetype
   fprintf(imageFile,"%d %d
",width,height);   // dimensions
   fprintf(imageFile,"255
");          // 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)

enter image description 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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...