Bitmap/Write a PPM file: Difference between revisions

From Rosetta Code
Content added Content deleted
(New page: {{task|Raster graphics operations}} Using the data storage type defined on this page for raster images, write the image to a PPM file (binary P6 prefered). <BR> (...)
 
(added C)
Line 3: Line 3:
Using the data storage type defined [[Basic_bitmap_storage|on this page]] for raster images, write the image to a PPM file (binary P6 prefered). <BR>
Using the data storage type defined [[Basic_bitmap_storage|on this page]] for raster images, write the image to a PPM file (binary P6 prefered). <BR>
(Read [http://en.wikipedia.org/wiki/Netpbm_format the definition of PPM file] on Wikipedia.)
(Read [http://en.wikipedia.org/wiki/Netpbm_format the definition of PPM file] on Wikipedia.)

=={{header|C}}==

<C>#include <stdio.h>

void output_ppm(FILE *fd, image img)
{
unsigned int n;
fprintf(fd, "P6\n%d %d\n255\n", img->width, img->height);
n = img->width * img->height;
fwrite(img->buf, sizeof(pixel), n, fd);
fflush(fd);
}</C>


== {{Header|OCaml}} ==
== {{Header|OCaml}} ==

Revision as of 12:13, 6 December 2008

Task
Bitmap/Write a PPM file
You are encouraged to solve this task according to the task description, using any language you may know.

Using the data storage type defined on this page for raster images, write the image to a PPM file (binary P6 prefered).
(Read the definition of PPM file on Wikipedia.)

C

<C>#include <stdio.h>

void output_ppm(FILE *fd, image img) {

   unsigned int n;
   fprintf(fd, "P6\n%d %d\n255\n", img->width, img->height);
   n = img->width * img->height;
   fwrite(img->buf, sizeof(pixel), n, fd);
   fflush(fd);

}</C>

OCaml

<ocaml>let output_ppm ~oc ~img:(_, r_channel, g_channel, b_channel) =

 let width = Bigarray.Array2.dim1 r_channel
 and height = Bigarray.Array2.dim2 r_channel in
 Printf.fprintf oc "P6\n%d %d\n255\n" width height;
 for y = 0 to pred height do
   for x = 0 to pred width do
     output_char oc (char_of_int r_channel.{x,y});
     output_char oc (char_of_int g_channel.{x,y});
     output_char oc (char_of_int b_channel.{x,y});
   done;
 done;
 output_char oc '\n';
 flush oc;
</ocaml>