Bitmap/Read an image through a pipe

From Rosetta Code
Revision as of 09:51, 13 May 2009 by rosettacode>Dkf (→‎{{header|Tcl}}: More modern magick!)
Task
Bitmap/Read an image through a pipe
You are encouraged to solve this task according to the task description, using any language you may know.

This task is the opposite of the PPM conversion through a pipe. In this task, using a delegate tool (like cjpeg, one of the netpbm package, or convert of the ImageMagick package) we read an image file and load it into the data storage type defined here. We can also use the code from Read ppm file, so that we can use PPM format like a (natural) bridge between the foreign image format and our simple data storage.


C

Works with: POSIX version .1-2001

Here I've used convert by ImageMagick. It is up to the program to understand the source file type; in this way, we can read theoretically any image format ImageMagick can handle. The get_ppm function defined in Read ppm file is used.

<lang c>image read_image(char *name);</lang>

<lang c>#include "imglib.h"

  1. define MAXCMDBUF 100
  2. define MAXFILENAMELEN 256
  3. define MAXFULLCMDBUF MAXCMDBUF+MAXFILENAMELEN

image read_image(char *name) {

     FILE *pipe;
     char buf[MAXFULLCMDBUF];
     image im;
     
     FILE *test = fopen(name, "r");
     if ( test == NULL ) {
        fprintf(stderr, "cannot open file %s\n", name);
        return NULL;
     }
     fclose(test);
     
     snprintf(buf, MAXFULLCMDBUF, "convert \"%s\" ppm:-", name);
     pipe = popen(buf, "r");
     if ( pipe != NULL )
     {
          im = get_ppm(pipe);
          pclose(pipe);
          return im;
     }
     return NULL;

}</lang>

Tcl

Works with: Tcl version 8.6
Library: Tk

<lang tcl>package require Tk

proc magickalReadImage {bufferImage fileName} {

   set f [open |[list convert [file normalize $fileName] ppm:-] "rb"]
   try {
       $bufferImage put [read $f] -format ppm
   } finally {
       close $f
   }

}</lang>