Bitmap/Read a PPM file: Difference between revisions

Content added Content deleted
m (syntax highlighting fixup automation)
m (Automated syntax highlighting fixup (second round - minor fixes))
Line 1: Line 1:
[[Category:Input Output]]
[[Category:E examples needing attention]]
{{task|Raster graphics operations}}
{{task|Raster graphics operations}}
[[Category:Input Output]]


Using the data storage type defined [[Basic_bitmap_storage|on this page]] for raster images, read an image from a PPM file (binary P6 prefered).
Using the data storage type defined [[Basic_bitmap_storage|on this page]] for raster images, read an image from a PPM file (binary P6 prefered).
Line 6: Line 7:


'''Task''': Use [[write ppm file]] solution and [[grayscale image]] solution with this one in order to convert a color image to grayscale one.
'''Task''': Use [[write ppm file]] solution and [[grayscale image]] solution with this one in order to convert a color image to grayscale one.

=={{header|11l}}==
=={{header|11l}}==
{{trans|Python}}
{{trans|Python}}


<syntaxhighlight lang=11l>T Colour
<syntaxhighlight lang="11l">T Colour
Byte r, g, b
Byte r, g, b


Line 121: Line 121:
4 4 4 0 0 0 0 0 0 0 0 0
4 4 4 0 0 0 0 0 0 0 0 0
</pre>
</pre>

=={{header|Action!}}==
=={{header|Action!}}==
Part of the task responsible for conversion from RGB color image into a grayscale image can be found in the module [http://www.rosettacode.org/wiki/Category:Action!_Bitmap_tools#RGB2GRAY.ACT RGB2GRAY.ACT]. File D:PPM6.PPM can be generated by task [http://www.rosettacode.org/wiki/Bitmap/Write_a_PPM_file#Action.21 Bitmap/Write a PPM file].
Part of the task responsible for conversion from RGB color image into a grayscale image can be found in the module [http://www.rosettacode.org/wiki/Category:Action!_Bitmap_tools#RGB2GRAY.ACT RGB2GRAY.ACT]. File D:PPM6.PPM can be generated by task [http://www.rosettacode.org/wiki/Bitmap/Write_a_PPM_file#Action.21 Bitmap/Write a PPM file].
{{libheader|Action! Bitmap tools}}
{{libheader|Action! Bitmap tools}}
{{libheader|Action! Tool Kit}}
{{libheader|Action! Tool Kit}}
<syntaxhighlight lang=Action!>INCLUDE "H6:RGB2GRAY.ACT" ;from task Grayscale image
<syntaxhighlight lang="action!">INCLUDE "H6:RGB2GRAY.ACT" ;from task Grayscale image


PROC DecodeSize(CHAR ARRAY s BYTE POINTER width,height)
PROC DecodeSize(CHAR ARRAY s BYTE POINTER width,height)
Line 281: Line 280:
45 54 74
45 54 74
</pre>
</pre>

=={{header|Ada}}==
=={{header|Ada}}==
<syntaxhighlight lang=ada>with Ada.Characters.Latin_1; use Ada.Characters.Latin_1;
<syntaxhighlight lang="ada">with Ada.Characters.Latin_1; use Ada.Characters.Latin_1;
with Ada.Integer_Text_IO; use Ada.Integer_Text_IO;
with Ada.Integer_Text_IO; use Ada.Integer_Text_IO;
with Ada.Streams.Stream_IO; use Ada.Streams.Stream_IO;
with Ada.Streams.Stream_IO; use Ada.Streams.Stream_IO;
Line 354: Line 352:
end Get_PPM;</syntaxhighlight>
end Get_PPM;</syntaxhighlight>
The implementation propagates Data_Error when the file format is incorrect. End_Error is propagated when the file end is prematurely met. The following example illustrates conversion of a color file to grayscale.
The implementation propagates Data_Error when the file format is incorrect. End_Error is propagated when the file end is prematurely met. The following example illustrates conversion of a color file to grayscale.
<syntaxhighlight lang=ada>declare
<syntaxhighlight lang="ada">declare
F1, F2 : File_Type;
F1, F2 : File_Type;
begin
begin
Line 363: Line 361:
Close (F2);
Close (F2);
end;</syntaxhighlight>
end;</syntaxhighlight>

=={{header|AutoHotkey}}==
=={{header|AutoHotkey}}==
{{works with | AutoHotkey_L}}
{{works with | AutoHotkey_L}}
Only ppm6 files supported.
Only ppm6 files supported.


<syntaxhighlight lang=AutoHotkey>img := ppm_read("lena50.ppm") ;
<syntaxhighlight lang="autohotkey">img := ppm_read("lena50.ppm") ;
x := img[4,4] ; get pixel(4,4)
x := img[4,4] ; get pixel(4,4)
y := img[24,24] ; get pixel(24,24)
y := img[24,24] ; get pixel(24,24)
Line 425: Line 422:
}
}
#include bitmap_storage.ahk ; from http://rosettacode.org/wiki/Basic_bitmap_storage/AutoHotkey</syntaxhighlight>
#include bitmap_storage.ahk ; from http://rosettacode.org/wiki/Basic_bitmap_storage/AutoHotkey</syntaxhighlight>

=={{header|BBC BASIC}}==
=={{header|BBC BASIC}}==
{{works with|BBC BASIC for Windows}}
{{works with|BBC BASIC for Windows}}
<syntaxhighlight lang=bbcbasic> f% = OPENIN("c:\lena.ppm")
<syntaxhighlight lang="bbcbasic"> f% = OPENIN("c:\lena.ppm")
IF f%=0 ERROR 100, "Failed to open input file"
IF f%=0 ERROR 100, "Failed to open input file"
Line 458: Line 454:
LINE x%*2,y%*2,x%*2,y%*2
LINE x%*2,y%*2,x%*2,y%*2
ENDPROC</syntaxhighlight>
ENDPROC</syntaxhighlight>

=={{header|C}}==
=={{header|C}}==
It is up to the caller to open the file and pass the handler to the function. So this code can be used in
It is up to the caller to open the file and pass the handler to the function. So this code can be used in
Line 465: Line 460:
Interface:
Interface:


<syntaxhighlight lang=c>image get_ppm(FILE *pf);</syntaxhighlight>
<syntaxhighlight lang="c">image get_ppm(FILE *pf);</syntaxhighlight>


Implementation:
Implementation:


<syntaxhighlight lang=c>#include "imglib.h"
<syntaxhighlight lang="c">#include "imglib.h"


#define PPMREADBUFLEN 256
#define PPMREADBUFLEN 256
Line 510: Line 505:
The following acts as a filter to convert a PPM file read from standard input into a PPM gray image, and it outputs the converted image to standard output (see [[Grayscale image]], [[Write ppm file]], and [[Raster graphics operations]] in general):
The following acts as a filter to convert a PPM file read from standard input into a PPM gray image, and it outputs the converted image to standard output (see [[Grayscale image]], [[Write ppm file]], and [[Raster graphics operations]] in general):


<syntaxhighlight lang=c>#include <stdio.h>
<syntaxhighlight lang="c">#include <stdio.h>
#include "imglib.h"
#include "imglib.h"


Line 526: Line 521:
return 0;
return 0;
}</syntaxhighlight>
}</syntaxhighlight>

=={{header|C sharp|C#}}==
=={{header|C sharp|C#}}==
Tested with [[Write ppm file#C.23|this solution.]]
Tested with [[Write ppm file#C.23|this solution.]]


<syntaxhighlight lang=csharp>using System.IO;
<syntaxhighlight lang="csharp">using System.IO;
class PPMReader
class PPMReader
{
{
Line 563: Line 557:
}
}
}</syntaxhighlight>
}</syntaxhighlight>

=={{header|Common Lisp}}==
=={{header|Common Lisp}}==


The function read-ppm-image reads either a P6 or P3 file depending on the file contents. The package description assumes that you have the [[Basic bitmap storage#Common Lisp]] package.
The function read-ppm-image reads either a P6 or P3 file depending on the file contents. The package description assumes that you have the [[Basic bitmap storage#Common Lisp]] package.


<syntaxhighlight lang=lisp>
<syntaxhighlight lang="lisp">
(in-package #:rgb-pixel-buffer)
(in-package #:rgb-pixel-buffer)


Line 642: Line 635:
</syntaxhighlight>
</syntaxhighlight>
To read the feep.ppm file as shown on the description page for the ppm format use:
To read the feep.ppm file as shown on the description page for the ppm format use:
<syntaxhighlight lang=lisp>
<syntaxhighlight lang="lisp">
(read-ppm-image "feep.ppm")
(read-ppm-image "feep.ppm")
</syntaxhighlight>
</syntaxhighlight>

=={{header|D}}==
=={{header|D}}==
The Image module contains a loadPPM6 function to load binary PPM images.
The Image module contains a loadPPM6 function to load binary PPM images.

=={{header|Delphi}}==
=={{header|Delphi}}==
Class helper for read and write Bitmap's and Ppm's
Class helper for read and write Bitmap's and Ppm's
{{Trans|C#}}
{{Trans|C#}}
<syntaxhighlight lang=Delphi>
<syntaxhighlight lang="delphi">
program BtmAndPpm;
program BtmAndPpm;


Line 781: Line 772:
end.
end.
</syntaxhighlight>
</syntaxhighlight>

=={{header|E}}==
=={{header|E}}==


<syntaxhighlight lang=e>def chr := <import:java.lang.makeCharacter>.asChar
<syntaxhighlight lang="e">def chr := <import:java.lang.makeCharacter>.asChar


def readPPM(inputStream) {
def readPPM(inputStream) {
Line 840: Line 830:
}</syntaxhighlight>
}</syntaxhighlight>


[[Category:E examples needing attention]]Note: As of this writing the [[grayscale image]] task has not been implemented, so the task code (below) won't actually run yet. But readPPM above has been tested separately.
Note: As of this writing the [[grayscale image]] task has not been implemented, so the task code (below) won't actually run yet. But readPPM above has been tested separately.


<syntaxhighlight lang=e>def readPPMTask(inputFile, outputFile) {
<syntaxhighlight lang="e">def readPPMTask(inputFile, outputFile) {
makeGrayscale \
makeGrayscale \
.fromColor(readPPM(<import:java.io.makeFileInputStream>(inputFile))) \
.fromColor(readPPM(<import:java.io.makeFileInputStream>(inputFile))) \
Line 848: Line 838:
.writePPM(<import:java.io.makeFileOutputStream>(outputFile))
.writePPM(<import:java.io.makeFileOutputStream>(outputFile))
}</syntaxhighlight>
}</syntaxhighlight>

=={{header|Erlang}}==
=={{header|Erlang}}==


<syntaxhighlight lang=erlang>
<syntaxhighlight lang="erlang">
% This module provides basic operations on ppm files:
% This module provides basic operations on ppm files:
% Read from file, create ppm in memory (from generic bitmap) and save to file.
% Read from file, create ppm in memory (from generic bitmap) and save to file.
Line 957: Line 946:


Usage in accordance with Grayscale Task:
Usage in accordance with Grayscale Task:
<syntaxhighlight lang=erlang>
<syntaxhighlight lang="erlang">
Colorful = ppm:read("colorful.ppm"),
Colorful = ppm:read("colorful.ppm"),
Gray = ros_bitmap:convert(ros_bitmap:convert(Colorful, grey), rgb),
Gray = ros_bitmap:convert(ros_bitmap:convert(Colorful, grey), rgb),
ppm:write(Gray, "gray.ppm"),
ppm:write(Gray, "gray.ppm"),
</syntaxhighlight>
</syntaxhighlight>

=={{header|Euphoria}}==
=={{header|Euphoria}}==
<syntaxhighlight lang=euphoria>include get.e
<syntaxhighlight lang="euphoria">include get.e


function get2(integer fn)
function get2(integer fn)
Line 1,007: Line 995:


Converting an image to grayscale:
Converting an image to grayscale:
<syntaxhighlight lang=euphoria>sequence image
<syntaxhighlight lang="euphoria">sequence image
image = read_ppm("image.ppm")
image = read_ppm("image.ppm")
image = to_gray(image)
image = to_gray(image)
image = to_color(image)
image = to_color(image)
write_ppm("image_gray.ppm",image)</syntaxhighlight>
write_ppm("image_gray.ppm",image)</syntaxhighlight>

=={{header|FBSL}}==
=={{header|FBSL}}==
Read a colored PPM file, convert it to grayscale and write back to disk under a different name. Sanity checks are omitted for brevity.
Read a colored PPM file, convert it to grayscale and write back to disk under a different name. Sanity checks are omitted for brevity.
Line 1,018: Line 1,005:
'''24-bpp P6 PPM solution:'''
'''24-bpp P6 PPM solution:'''
[[File:FBSLLena.png|right]]
[[File:FBSLLena.png|right]]
<syntaxhighlight lang=qbasic>#ESCAPECHARS ON
<syntaxhighlight lang="qbasic">#ESCAPECHARS ON


DIM colored = ".\\Lena.ppm", grayscale = ".\\LenaGry.ppm"
DIM colored = ".\\Lena.ppm", grayscale = ".\\LenaGry.ppm"
Line 1,036: Line 1,023:


FILEPUT(FILEOPEN(grayscale, BINARY_NEW), FILEGET): FILECLOSE(FILEOPEN) ' Save buffer</syntaxhighlight>
FILEPUT(FILEOPEN(grayscale, BINARY_NEW), FILEGET): FILECLOSE(FILEOPEN) ' Save buffer</syntaxhighlight>

=={{header|Forth}}==
=={{header|Forth}}==
<syntaxhighlight lang=forth>: read-ppm { fid -- bmp }
<syntaxhighlight lang="forth">: read-ppm { fid -- bmp }
pad dup 80 fid read-line throw 0= abort" Partial line"
pad dup 80 fid read-line throw 0= abort" Partial line"
s" P6" compare abort" Only P6 supported."
s" P6" compare abort" Only P6 supported."
Line 1,076: Line 1,062:


test dup bsize test2 dup bsize compare . \ 0 if identical</syntaxhighlight>
test dup bsize test2 dup bsize compare . \ 0 if identical</syntaxhighlight>

=={{header|Fortran}}==
=={{header|Fortran}}==
{{works with|Fortran|90 and later}}
{{works with|Fortran|90 and later}}
Line 1,082: Line 1,067:
(This function is part of module RCImageIO, see [[Write ppm file#Fortran|Write ppm file]])
(This function is part of module RCImageIO, see [[Write ppm file#Fortran|Write ppm file]])


<syntaxhighlight lang=fortran>subroutine read_ppm(u, img)
<syntaxhighlight lang="fortran">subroutine read_ppm(u, img)
integer, intent(in) :: u
integer, intent(in) :: u
type(rgbimage), intent(out) :: img
type(rgbimage), intent(out) :: img
Line 1,129: Line 1,114:
* doing formatted I/O with Fortran is a pain... And unformatted does not mean ''free''; Fortran2003 has ''streams'', but they are not implemented (yet) in GNU Fortran compiler. Here (as in the write part) I've tried to handle the PPM format through formatted I/O. The tests worked but I have not tried still everything.
* doing formatted I/O with Fortran is a pain... And unformatted does not mean ''free''; Fortran2003 has ''streams'', but they are not implemented (yet) in GNU Fortran compiler. Here (as in the write part) I've tried to handle the PPM format through formatted I/O. The tests worked but I have not tried still everything.
* comments after the first line are not handled
* comments after the first line are not handled

=={{header|Go}}==
=={{header|Go}}==
<syntaxhighlight lang=go>package raster
<syntaxhighlight lang="go">package raster


import (
import (
Line 1,200: Line 1,184:
}</syntaxhighlight>
}</syntaxhighlight>
Demonstration program, also demonstrating functions from task [[Grayscale image]]:
Demonstration program, also demonstrating functions from task [[Grayscale image]]:
<syntaxhighlight lang=go>package main
<syntaxhighlight lang="go">package main


// Files required to build supporting package raster are found in:
// Files required to build supporting package raster are found in:
Line 1,228: Line 1,212:
}
}
}</syntaxhighlight>
}</syntaxhighlight>

=={{header|Haskell}}==
=={{header|Haskell}}==
The definition of <tt>Bitmap.Netpbm.readNetpbm</tt> is given [[Write ppm file|here]].
The definition of <tt>Bitmap.Netpbm.readNetpbm</tt> is given [[Write ppm file|here]].
<syntaxhighlight lang=haskell>import Bitmap
<syntaxhighlight lang="haskell">import Bitmap
import Bitmap.RGB
import Bitmap.RGB
import Bitmap.Gray
import Bitmap.Gray
Line 1,244: Line 1,227:
writeNetpbm "new.pgm"</syntaxhighlight>
writeNetpbm "new.pgm"</syntaxhighlight>
The above writes a PGM, not a PPM, since the image being output is in grayscale. If you actually want a gray PPM, convert the <tt>Image RealWorld Gray</tt> back to an <tt>Image RealWorld RGB</tt> first:
The above writes a PGM, not a PPM, since the image being output is in grayscale. If you actually want a gray PPM, convert the <tt>Image RealWorld Gray</tt> back to an <tt>Image RealWorld RGB</tt> first:
<syntaxhighlight lang=haskell>main =
<syntaxhighlight lang="haskell">main =
(readNetpbm "original.ppm" :: IO (Image RealWorld RGB)) >>=
(readNetpbm "original.ppm" :: IO (Image RealWorld RGB)) >>=
stToIO . (toRGBImage <=< toGrayImage) >>=
stToIO . (toRGBImage <=< toGrayImage) >>=
writeNetpbm "new.ppm"</syntaxhighlight>
writeNetpbm "new.ppm"</syntaxhighlight>

=={{header|J}}==
=={{header|J}}==
'''Solution:'''<br>
'''Solution:'''<br>
Uses <tt>makeRGB</tt> from [[Basic bitmap storage#J|Basic bitmap storage]].
Uses <tt>makeRGB</tt> from [[Basic bitmap storage#J|Basic bitmap storage]].
<syntaxhighlight lang=j>require 'files'
<syntaxhighlight lang="j">require 'files'


readppm=: monad define
readppm=: monad define
Line 1,266: Line 1,248:
Using utilities and file from [[Grayscale image#J|Grayscale image]] and [[Write ppm file#J|Write ppm file]].<br>
Using utilities and file from [[Grayscale image#J|Grayscale image]] and [[Write ppm file#J|Write ppm file]].<br>
Writes a gray PPM file (a color format) which is bigger than necessary. A PGM file would be more appropriate.
Writes a gray PPM file (a color format) which is bigger than necessary. A PGM file would be more appropriate.
<syntaxhighlight lang=j>myimg=: readppm jpath '~temp/myimg.ppm'
<syntaxhighlight lang="j">myimg=: readppm jpath '~temp/myimg.ppm'
myimgGray=: toColor toGray myimg
myimgGray=: toColor toGray myimg
myimgGray writeppm jpath '~temp/myimgGray.ppm'</syntaxhighlight>
myimgGray writeppm jpath '~temp/myimgGray.ppm'</syntaxhighlight>

=={{header|Julia}}==
=={{header|Julia}}==
{{works with|Julia|0.6}}
{{works with|Julia|0.6}}


<syntaxhighlight lang=julia>using Images, FileIO, Netpbm
<syntaxhighlight lang="julia">using Images, FileIO, Netpbm


rgbimg = load("data/bitmapInputTest.ppm")
rgbimg = load("data/bitmapInputTest.ppm")
greyimg = Gray.(rgbimg)
greyimg = Gray.(rgbimg)
save("data/bitmapOutputTest.ppm", greyimg)</syntaxhighlight>
save("data/bitmapOutputTest.ppm", greyimg)</syntaxhighlight>

=={{header|Kotlin}}==
=={{header|Kotlin}}==
For convenience, we repeat the code for the class used in the [[Bitmap]] task here and integrate the code in the [[Grayscale image]] task within it.
For convenience, we repeat the code for the class used in the [[Bitmap]] task here and integrate the code in the [[Grayscale image]] task within it.
<syntaxhighlight lang=scala>// Version 1.2.40
<syntaxhighlight lang="scala">// Version 1.2.40


import java.awt.Color
import java.awt.Color
Line 1,411: Line 1,391:
}
}
}</syntaxhighlight>
}</syntaxhighlight>

=={{header|Lua}}==
=={{header|Lua}}==
<syntaxhighlight lang=lua>function Read_PPM( filename )
<syntaxhighlight lang="lua">function Read_PPM( filename )
local fp = io.open( filename, "rb" )
local fp = io.open( filename, "rb" )
if fp == nil then return nil end
if fp == nil then return nil end
Line 1,447: Line 1,426:
return image
return image
end</syntaxhighlight>
end</syntaxhighlight>

=={{header|M2000 Interpreter}}==
=={{header|M2000 Interpreter}}==
Now function Bitmap has double signature. With two numbers make a bitmap,with all pixels white. With one number, expect that it is a file number and read file, and then return the bitmap.
Now function Bitmap has double signature. With two numbers make a bitmap,with all pixels white. With one number, expect that it is a file number and read file, and then return the bitmap.


<syntaxhighlight lang=M2000 Interpreter>
<syntaxhighlight lang="m2000 interpreter">
Module Checkit {
Module Checkit {
Function Bitmap {
Function Bitmap {
Line 1,623: Line 1,601:


</syntaxhighlight>
</syntaxhighlight>

=={{header|Mathematica}}/ {{header|Wolfram Language}}==
=={{header|Mathematica}}/ {{header|Wolfram Language}}==
<syntaxhighlight lang=Mathematica>Import["file.ppm","PPM"]
<syntaxhighlight lang="mathematica">Import["file.ppm","PPM"]
</syntaxhighlight>
</syntaxhighlight>

=={{header|Nim}}==
=={{header|Nim}}==
<syntaxhighlight lang=nim>import strutils
<syntaxhighlight lang="nim">import strutils
import bitmap
import bitmap
import streams
import streams
Line 1,720: Line 1,696:
let image = readPPM("output.ppm")
let image = readPPM("output.ppm")
echo image.h, " ", image.w</syntaxhighlight>
echo image.h, " ", image.w</syntaxhighlight>

=={{header|OCaml}}==
=={{header|OCaml}}==


<syntaxhighlight lang=ocaml>let read_ppm ~filename =
<syntaxhighlight lang="ocaml">let read_ppm ~filename =
let ic = open_in filename in
let ic = open_in filename in
let line = input_line ic in
let line = input_line ic in
Line 1,763: Line 1,738:


and converting a given color file to grayscale:
and converting a given color file to grayscale:
<syntaxhighlight lang=ocaml>let () =
<syntaxhighlight lang="ocaml">let () =
let img = read_ppm ~filename:"logo.ppm" in
let img = read_ppm ~filename:"logo.ppm" in
let img = to_color(to_grayscale ~img) in
let img = to_color(to_grayscale ~img) in
Line 1,770: Line 1,745:
sending the result to <tt>stdout</tt> allows to see the result without creating a temporary file sending it through a pipe to the '''display''' utility of ''ImageMagick'':
sending the result to <tt>stdout</tt> allows to see the result without creating a temporary file sending it through a pipe to the '''display''' utility of ''ImageMagick'':
ocaml script.ml | display -
ocaml script.ml | display -

=={{header|Oz}}==
=={{header|Oz}}==
The read function in module <code>"BitmapIO.oz"</code>:
The read function in module <code>"BitmapIO.oz"</code>:
<syntaxhighlight lang=oz>functor
<syntaxhighlight lang="oz">functor
import
import
Bitmap
Bitmap
Line 1,859: Line 1,833:


The actual task:
The actual task:
<syntaxhighlight lang=oz>declare
<syntaxhighlight lang="oz">declare
[BitmapIO Grayscale] = {Module.link ['BitmapIO.ozf' 'Grayscale.ozf']}
[BitmapIO Grayscale] = {Module.link ['BitmapIO.ozf' 'Grayscale.ozf']}


Line 1,866: Line 1,840:
in
in
{BitmapIO.write {Grayscale.fromGraymap G} "greyimage.ppm"}</syntaxhighlight>
{BitmapIO.write {Grayscale.fromGraymap G} "greyimage.ppm"}</syntaxhighlight>

=={{header|Perl}}==
=={{header|Perl}}==


{{libheader|Imlib2}}
{{libheader|Imlib2}}


<syntaxhighlight lang=perl>#! /usr/bin/perl
<syntaxhighlight lang="perl">#! /usr/bin/perl


use strict;
use strict;
Line 1,885: Line 1,858:


exit 0;</syntaxhighlight>
exit 0;</syntaxhighlight>

=={{header|Phix}}==
=={{header|Phix}}==
Based on [[Bitmap/Read_a_PPM_file#Euphoria|Euphoria]], requires write_ppm() from [[Bitmap/Write_a_PPM_file#Phix|Write_a_PPM_file]], to_grey from [[Grayscale_image#Phix|Grayscale_image]]<br>
Based on [[Bitmap/Read_a_PPM_file#Euphoria|Euphoria]], requires write_ppm() from [[Bitmap/Write_a_PPM_file#Phix|Write_a_PPM_file]], to_grey from [[Grayscale_image#Phix|Grayscale_image]]<br>
Note that demo\rosetta\Bitmap_read_ppm.exw is just the last 3 lines with the include ppm.e since that contains the read_ppm() (abeit with a few more options and other tweaks) also used by several other examples, and covers the above requirements. Results may be verified with demo\rosetta\viewppm.exw
Note that demo\rosetta\Bitmap_read_ppm.exw is just the last 3 lines with the include ppm.e since that contains the read_ppm() (abeit with a few more options and other tweaks) also used by several other examples, and covers the above requirements. Results may be verified with demo\rosetta\viewppm.exw
<syntaxhighlight lang=Phix>-- demo\rosetta\Bitmap_read_ppm.exw (runnable version)
<syntaxhighlight lang="phix">-- demo\rosetta\Bitmap_read_ppm.exw (runnable version)


function read_ppm(string filename)
function read_ppm(string filename)
Line 1,921: Line 1,893:
img = to_grey(img)
img = to_grey(img)
write_ppm("LenaGray.ppm",img)</syntaxhighlight>
write_ppm("LenaGray.ppm",img)</syntaxhighlight>

=={{header|PicoLisp}}==
=={{header|PicoLisp}}==
<syntaxhighlight lang=PicoLisp>(de ppmRead (File)
<syntaxhighlight lang="picolisp">(de ppmRead (File)
(in File
(in File
(unless (and `(hex "5036") (rd 2)) # P6
(unless (and `(hex "5036") (rd 2)) # P6
Line 1,942: Line 1,913:
Y ) ) ) ) ) )</syntaxhighlight>
Y ) ) ) ) ) )</syntaxhighlight>
Read a color image "img.ppm", convert and write to "img.pgm":
Read a color image "img.ppm", convert and write to "img.pgm":
<syntaxhighlight lang=PicoLisp>(pgmWrite (ppm->pgm (ppmRead "img.ppm")) "img.pgm")</syntaxhighlight>
<syntaxhighlight lang="picolisp">(pgmWrite (ppm->pgm (ppmRead "img.ppm")) "img.pgm")</syntaxhighlight>

=={{header|PL/I}}==
=={{header|PL/I}}==
<syntaxhighlight lang=PL/I>
<syntaxhighlight lang="pl/i">
/* BITMAP FILE: read in a file in PPM format, P6 (binary). 14/5/2010 */
/* BITMAP FILE: read in a file in PPM format, P6 (binary). 14/5/2010 */
test: procedure options (main);
test: procedure options (main);
Line 2,010: Line 1,980:
end is_digit;
end is_digit;
end test;</syntaxhighlight>
end test;</syntaxhighlight>

=={{header|PureBasic}}==
=={{header|PureBasic}}==
<syntaxhighlight lang=PureBasic>Structure PPMColor
<syntaxhighlight lang="purebasic">Structure PPMColor
r.c
r.c
g.c
g.c
Line 2,072: Line 2,041:


To complete the task, the following code should be added to the above fragment and to the PureBasic solutions for [[Grayscale_image#PureBasic|Grayscale image]] and [[Bitmap/Write_a_PPM_file#PureBasic|Write a PPM file]]
To complete the task, the following code should be added to the above fragment and to the PureBasic solutions for [[Grayscale_image#PureBasic|Grayscale image]] and [[Bitmap/Write_a_PPM_file#PureBasic|Write a PPM file]]
<syntaxhighlight lang=PureBasic>Define file.s, file2.s, image = 3
<syntaxhighlight lang="purebasic">Define file.s, file2.s, image = 3
file = OpenFileRequester("Select source image file", "", "PPM image (*.ppm)|*.ppm", 0)
file = OpenFileRequester("Select source image file", "", "PPM image (*.ppm)|*.ppm", 0)
If file And LCase(GetExtensionPart(file)) = "ppm"
If file And LCase(GetExtensionPart(file)) = "ppm"
Line 2,080: Line 2,049:
SaveImageAsPPM(image, file2, 1)
SaveImageAsPPM(image, file2, 1)
EndIf</syntaxhighlight>
EndIf</syntaxhighlight>

=={{header|Python}}==
=={{header|Python}}==
{{works with|Python|3.1}}
{{works with|Python|3.1}}


Extending the example given [[Basic_bitmap_storage#Alternative_version|here]]
Extending the example given [[Basic_bitmap_storage#Alternative_version|here]]
<syntaxhighlight lang=python># With help from http://netpbm.sourceforge.net/doc/ppm.html
<syntaxhighlight lang="python"># With help from http://netpbm.sourceforge.net/doc/ppm.html


# String masquerading as ppm file (version P3)
# String masquerading as ppm file (version P3)
Line 2,154: Line 2,122:


'''</syntaxhighlight>
'''</syntaxhighlight>

=={{header|Racket}}==
=={{header|Racket}}==
<syntaxhighlight lang=racket>
<syntaxhighlight lang="racket">
#lang racket
#lang racket
(require racket/draw)
(require racket/draw)
Line 2,180: Line 2,147:
bm))
bm))
</syntaxhighlight>
</syntaxhighlight>

=={{header|Raku}}==
=={{header|Raku}}==
(formerly Perl 6)
(formerly Perl 6)
Line 2,186: Line 2,152:
Uses pieces from [[Bitmap#Raku| Bitmap]], [[Bitmap/Write_a_PPM_file#Raku| Write a PPM file]] and [[Grayscale_image#Raku| Grayscale image]] tasks. Included here to make a complete, runnable program.
Uses pieces from [[Bitmap#Raku| Bitmap]], [[Bitmap/Write_a_PPM_file#Raku| Write a PPM file]] and [[Grayscale_image#Raku| Grayscale image]] tasks. Included here to make a complete, runnable program.


<syntaxhighlight lang=raku line>class Pixel { has UInt ($.R, $.G, $.B) }
<syntaxhighlight lang="raku" line>class Pixel { has UInt ($.R, $.G, $.B) }
class Bitmap {
class Bitmap {
has UInt ($.width, $.height);
has UInt ($.width, $.height);
Line 2,224: Line 2,190:


See [https://github.com/thundergnat/rc/blob/master/img/camelia.png camelia], and [https://github.com/thundergnat/rc/blob/master/img/camelia-gs.png camelia-gs] images. (converted to .png as .ppm format is not widely supported).
See [https://github.com/thundergnat/rc/blob/master/img/camelia.png camelia], and [https://github.com/thundergnat/rc/blob/master/img/camelia-gs.png camelia-gs] images. (converted to .png as .ppm format is not widely supported).

=={{header|REXX}}==
=={{header|REXX}}==
The input file &nbsp; '''Lenna50.ppm''' &nbsp; is a '''PPM''' format of
The input file &nbsp; '''Lenna50.ppm''' &nbsp; is a '''PPM''' format of
Line 2,230: Line 2,195:


This REXX program handles alternative delimiters as well as comments within the PPM header.
This REXX program handles alternative delimiters as well as comments within the PPM header.
<syntaxhighlight lang=rexx>/*REXX program reads a PPM formatted image file, and creates a gray─scale image of it. */
<syntaxhighlight lang="rexx">/*REXX program reads a PPM formatted image file, and creates a gray─scale image of it. */
parse arg iFN oFN /*obtain optional argument from the CL.*/
parse arg iFN oFN /*obtain optional argument from the CL.*/
if iFN=='' | iFN=="," then iFN= 'Lenna50' /*Not specified? Then use the default.*/
if iFN=='' | iFN=="," then iFN= 'Lenna50' /*Not specified? Then use the default.*/
Line 2,270: Line 2,235:
File greyscale.ppm was created.
File greyscale.ppm was created.
</pre>
</pre>

=={{header|Ruby}}==
=={{header|Ruby}}==
Extending [[Basic_bitmap_storage#Ruby]]
Extending [[Basic_bitmap_storage#Ruby]]
<syntaxhighlight lang=ruby>class Pixmap
<syntaxhighlight lang="ruby">class Pixmap
# 'open' is a class method
# 'open' is a class method
def self.open(filename)
def self.open(filename)
Line 2,306: Line 2,270:
# then, convert to grayscale
# then, convert to grayscale
Pixmap.open('testcross.ppm').to_grayscale!.save('testgray.ppm')</syntaxhighlight>
Pixmap.open('testcross.ppm').to_grayscale!.save('testgray.ppm')</syntaxhighlight>

=={{header|Rust}}==
=={{header|Rust}}==
<syntaxhighlight lang=rust>
<syntaxhighlight lang="rust">
parser.rs:
parser.rs:
use super::{Color, ImageFormat};
use super::{Color, ImageFormat};
Line 2,592: Line 2,555:
}
}
</syntaxhighlight>
</syntaxhighlight>


=={{header|Scala}}==
=={{header|Scala}}==
Uses the [[Basic_bitmap_storage#Scala|Basic Bitmap Storage]] and [[Grayscale_image#Scala|Grayscale Bitmap]] classes.
Uses the [[Basic_bitmap_storage#Scala|Basic Bitmap Storage]] and [[Grayscale_image#Scala|Grayscale Bitmap]] classes.
Line 2,599: Line 2,560:
See also Task [[Write_ppm_file#Scala|Write a PPM File]] for save code.
See also Task [[Write_ppm_file#Scala|Write a PPM File]] for save code.


<syntaxhighlight lang=scala>import scala.io._
<syntaxhighlight lang="scala">import scala.io._
import scala.swing._
import scala.swing._
import java.io._
import java.io._
Line 2,647: Line 2,608:


Usage:
Usage:
<syntaxhighlight lang=scala>object PixmapTest {
<syntaxhighlight lang="scala">object PixmapTest {
def main(args: Array[String]): Unit = {
def main(args: Array[String]): Unit = {
val img=Pixmap.load("image.ppm").get
val img=Pixmap.load("image.ppm").get
Line 2,662: Line 2,623:
}
}
}</syntaxhighlight>
}</syntaxhighlight>

=={{header|Seed7}}==
=={{header|Seed7}}==
<syntaxhighlight lang=seed7>$ include "seed7_05.s7i";
<syntaxhighlight lang="seed7">$ include "seed7_05.s7i";
include "draw.s7i";
include "draw.s7i";
include "color.s7i";
include "color.s7i";
Line 2,700: Line 2,660:
end if;
end if;
end func;</syntaxhighlight>
end func;</syntaxhighlight>

=={{header|Tcl}}==
=={{header|Tcl}}==
{{libheader|Tk}}
{{libheader|Tk}}
The actual PPM reader is built into the photo image engine:
The actual PPM reader is built into the photo image engine:
<syntaxhighlight lang=tcl>package require Tk
<syntaxhighlight lang="tcl">package require Tk


proc readPPM {image file} {
proc readPPM {image file} {
Line 2,710: Line 2,669:
}</syntaxhighlight>
}</syntaxhighlight>
Thus, to read a PPM, convert it to grayscale, and write it back out again becomes this (which requires Tcl 8.6 for <code>try</code>/<code>finally</code>); the PPM reader and writer are inlined because they are trivial at the script level:
Thus, to read a PPM, convert it to grayscale, and write it back out again becomes this (which requires Tcl 8.6 for <code>try</code>/<code>finally</code>); the PPM reader and writer are inlined because they are trivial at the script level:
<syntaxhighlight lang=tcl>package require Tk
<syntaxhighlight lang="tcl">package require Tk


proc grayscaleFile {filename {newFilename ""}} {
proc grayscaleFile {filename {newFilename ""}} {
Line 2,733: Line 2,692:


However, the Tk library also has built-in the ability to convert code to grayscale directly during the saving of an image to a file, leading to this minimal solution:
However, the Tk library also has built-in the ability to convert code to grayscale directly during the saving of an image to a file, leading to this minimal solution:
<syntaxhighlight lang=tcl>package require Tk
<syntaxhighlight lang="tcl">package require Tk


proc grayscaleFile {filename {newFilename ""}} {
proc grayscaleFile {filename {newFilename ""}} {
Line 2,745: Line 2,704:
}
}
}</syntaxhighlight>
}</syntaxhighlight>

=={{header|UNIX Shell}}==
=={{header|UNIX Shell}}==
{{works with|ksh93}}
{{works with|ksh93}}
Line 2,751: Line 2,709:


Add the following functions to the <tt>RGBColor_t</tt> type
Add the following functions to the <tt>RGBColor_t</tt> type
<syntaxhighlight lang=bash> function setrgb {
<syntaxhighlight lang="bash"> function setrgb {
_.r=$1
_.r=$1
_.g=$2
_.g=$2
Line 2,764: Line 2,722:


Add the following function to the <tt>Bitmap_t</tt> type
Add the following function to the <tt>Bitmap_t</tt> type
<syntaxhighlight lang=bash> function grayscale {
<syntaxhighlight lang="bash"> function grayscale {
RGBColor_t c
RGBColor_t c
for ((y=0; y<_.height; y++)); do
for ((y=0; y<_.height; y++)); do
Line 2,805: Line 2,763:


Now we can:
Now we can:
<syntaxhighlight lang=bash>Bitmap_t c
<syntaxhighlight lang="bash">Bitmap_t c
c.read "$HOME/tmp/bitmap.ppm"
c.read "$HOME/tmp/bitmap.ppm"
c.to_s
c.to_s
Line 2,818: Line 2,776:
c.to_s
c.to_s
c.write "$HOME/tmp/bitmap_g.ppm"</syntaxhighlight>
c.write "$HOME/tmp/bitmap_g.ppm"</syntaxhighlight>

=={{header|Vedit macro language}}==
=={{header|Vedit macro language}}==
<syntaxhighlight lang=vedit>// Load a PPM file
<syntaxhighlight lang="vedit">// Load a PPM file
// @10 = filename
// @10 = filename
// On return:
// On return:
Line 2,839: Line 2,796:


Example of usage. In addition to LOAD_PPM routine above, you need routine RGB_TO_GRAYSCALE from [[Grayscale image]] and routine SAVE_PPM from [[Write ppm file]].
Example of usage. In addition to LOAD_PPM routine above, you need routine RGB_TO_GRAYSCALE from [[Grayscale image]] and routine SAVE_PPM from [[Write ppm file]].
<syntaxhighlight lang=vedit>// Load RGB image
<syntaxhighlight lang="vedit">// Load RGB image
Reg_Set(10, "|(USER_MACRO)\example.ppm")
Reg_Set(10, "|(USER_MACRO)\example.ppm")
Call("LOAD_PPM")
Call("LOAD_PPM")
Line 2,858: Line 2,815:
Buf_Switch(#20) Buf_Quit(OK)
Buf_Switch(#20) Buf_Quit(OK)
return</syntaxhighlight>
return</syntaxhighlight>

=={{header|Wren}}==
=={{header|Wren}}==
{{libheader|DOME}}
{{libheader|DOME}}
This assumes that [https://rosettacode.org/wiki/File:Lenna100.jpg Lenna100.jpg], a 512 x 512 color image of the eponymous lady, has already been converted to Lenna100.ppm using a variation of the 'Write a PPM file' task.
This assumes that [https://rosettacode.org/wiki/File:Lenna100.jpg Lenna100.jpg], a 512 x 512 color image of the eponymous lady, has already been converted to Lenna100.ppm using a variation of the 'Write a PPM file' task.
<syntaxhighlight lang=ecmascript>import "graphics" for Canvas, ImageData, Color
<syntaxhighlight lang="ecmascript">import "graphics" for Canvas, ImageData, Color
import "dome" for Window, Process
import "dome" for Window, Process
import "io" for FileSystem
import "io" for FileSystem
Line 2,937: Line 2,893:


var Game = Bitmap.new("Lenna100.ppm", "Lenna100_gs.jpg", 1048, 512)</syntaxhighlight>
var Game = Bitmap.new("Lenna100.ppm", "Lenna100_gs.jpg", 1048, 512)</syntaxhighlight>

=={{header|XPL0}}==
=={{header|XPL0}}==
The simplicity of redirecting an input file on the command line doesn't
The simplicity of redirecting an input file on the command line doesn't
Line 2,943: Line 2,898:
files larger than 1280x1024 are clipped to the screen dimensions.
files larger than 1280x1024 are clipped to the screen dimensions.


<syntaxhighlight lang=XPL0>include c:\cxpl\codes; \intrinsic 'code' declarations
<syntaxhighlight lang="xpl0">include c:\cxpl\codes; \intrinsic 'code' declarations


func OpenInFile; \Open for input the file typed on command line
func OpenInFile; \Open for input the file typed on command line
Line 2,988: Line 2,943:
SetVid(3); \restore normal text display
SetVid(3); \restore normal text display
]</syntaxhighlight>
]</syntaxhighlight>

=={{header|Yabasic}}==
=={{header|Yabasic}}==
<syntaxhighlight lang=Yabasic>sub readPPM(f$)
<syntaxhighlight lang="yabasic">sub readPPM(f$)
local ff, x, y, t$, dcol$, wid, hei
local ff, x, y, t$, dcol$, wid, hei


Line 3,017: Line 2,971:
return true
return true
end sub</syntaxhighlight>
end sub</syntaxhighlight>

=={{header|zkl}}==
=={{header|zkl}}==
{{trans|FBSL}}
{{trans|FBSL}}
Line 3,024: Line 2,977:
I used a slightly different image from what is shown, but the results are the same.
I used a slightly different image from what is shown, but the results are the same.
[[File:FBSLLena.png|right]]
[[File:FBSLLena.png|right]]
<syntaxhighlight lang=zkl>//24-bpp P6 PPM solution:
<syntaxhighlight lang="zkl">//24-bpp P6 PPM solution:
image:=File("lena.ppm","rb").read();
image:=File("lena.ppm","rb").read();
start:=image.find("\n255\n")+5; // Get sizeof PPM header
start:=image.find("\n255\n")+5; // Get sizeof PPM header
Line 3,035: Line 2,988:


File("lenaGrey.ppm","wb").write(image);</syntaxhighlight>
File("lenaGrey.ppm","wb").write(image);</syntaxhighlight>



{{omit from|AWK}}
{{omit from|AWK}}
{{omit from|Lotus 123 Macro Scripting}}
{{omit from|Lotus 123 Macro Scripting}}