Bitmap/Read a PPM file: Difference between revisions

Content added Content deleted
(Added solution for Action!)
m (syntax highlighting fixup automation)
Line 10: Line 10:
{{trans|Python}}
{{trans|Python}}


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


Line 107: Line 107:
print(‘Grey PPM:’)
print(‘Grey PPM:’)
bitmap.togreyscale()
bitmap.togreyscale()
print(bitmap.writeppmp3())</lang>
print(bitmap.writeppmp3())</syntaxhighlight>


{{out}}
{{out}}
Line 126: Line 126:
{{libheader|Action! Bitmap tools}}
{{libheader|Action! Bitmap tools}}
{{libheader|Action! Tool Kit}}
{{libheader|Action! Tool Kit}}
<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 261: Line 261:
PrintF("Loading %S...%E%E",path2)
PrintF("Loading %S...%E%E",path2)
Load(path2)
Load(path2)
RETURN</lang>
RETURN</syntaxhighlight>
{{out}}
{{out}}
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Read_a_PPM_file.png Screenshot from Atari 8-bit computer]
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Read_a_PPM_file.png Screenshot from Atari 8-bit computer]
Line 283: Line 283:


=={{header|Ada}}==
=={{header|Ada}}==
<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 352: Line 352:
return Result;
return Result;
end;
end;
end Get_PPM;</lang>
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.
<lang ada>declare
<syntaxhighlight lang=ada>declare
F1, F2 : File_Type;
F1, F2 : File_Type;
begin
begin
Line 362: Line 362:
Close (F1);
Close (F1);
Close (F2);
Close (F2);
end;</lang>
end;</syntaxhighlight>


=={{header|AutoHotkey}}==
=={{header|AutoHotkey}}==
Line 368: Line 368:
Only ppm6 files supported.
Only ppm6 files supported.


<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 424: Line 424:
return bitmap
return bitmap
}
}
#include bitmap_storage.ahk ; from http://rosettacode.org/wiki/Basic_bitmap_storage/AutoHotkey</lang>
#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}}
<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 457: Line 457:
GCOL 1
GCOL 1
LINE x%*2,y%*2,x%*2,y%*2
LINE x%*2,y%*2,x%*2,y%*2
ENDPROC</lang>
ENDPROC</syntaxhighlight>


=={{header|C}}==
=={{header|C}}==
Line 465: Line 465:
Interface:
Interface:


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


Implementation:
Implementation:


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


#define PPMREADBUFLEN 256
#define PPMREADBUFLEN 256
Line 506: Line 506:
return img;
return img;
}
}
}</lang>
}</syntaxhighlight>


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):


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


Line 525: Line 525:
free_img(source); free_img((image)idest);
free_img(source); free_img((image)idest);
return 0;
return 0;
}</lang>
}</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.]]


<lang csharp>using System.IO;
<syntaxhighlight lang=csharp>using System.IO;
class PPMReader
class PPMReader
{
{
Line 562: Line 562:
return bitmap;
return bitmap;
}
}
}</lang>
}</syntaxhighlight>


=={{header|Common Lisp}}==
=={{header|Common Lisp}}==
Line 568: Line 568:
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.


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


Line 640: Line 640:


(export 'read-ppm-image)
(export 'read-ppm-image)
</syntaxhighlight>
</lang>
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:
<lang lisp>
<syntaxhighlight lang=lisp>
(read-ppm-image "feep.ppm")
(read-ppm-image "feep.ppm")
</syntaxhighlight>
</lang>


=={{header|D}}==
=={{header|D}}==
Line 652: Line 652:
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#}}
<lang Delphi>
<syntaxhighlight lang=Delphi>
program BtmAndPpm;
program BtmAndPpm;


Line 780: Line 780:
end;
end;
end.
end.
</syntaxhighlight>
</lang>


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


<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 838: Line 838:
image.replace(data.snapshot())
image.replace(data.snapshot())
return image
return image
}</lang>
}</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.
[[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.


<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))) \
.toColor() \
.toColor() \
.writePPM(<import:java.io.makeFileOutputStream>(outputFile))
.writePPM(<import:java.io.makeFileOutputStream>(outputFile))
}</lang>
}</syntaxhighlight>


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


<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 954: Line 954:
encode_decimal(Number) ->
encode_decimal(Number) ->
integer_to_list(Number).
integer_to_list(Number).
</syntaxhighlight>
</lang>


Usage in accordance with Grayscale Task:
Usage in accordance with Grayscale Task:
<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>
</lang>


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


function get2(integer fn)
function get2(integer fn)
Line 1,004: Line 1,004:
close(fn)
close(fn)
return image
return image
end function</lang>
end function</syntaxhighlight>


Converting an image to grayscale:
Converting an image to grayscale:
<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)</lang>
write_ppm("image_gray.ppm",image)</syntaxhighlight>


=={{header|FBSL}}==
=={{header|FBSL}}==
Line 1,018: Line 1,018:
'''24-bpp P6 PPM solution:'''
'''24-bpp P6 PPM solution:'''
[[File:FBSLLena.png|right]]
[[File:FBSLLena.png|right]]
<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,035: Line 1,035:
NEXT
NEXT


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


=={{header|Forth}}==
=={{header|Forth}}==
<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,075: Line 1,075:
: bsize ( bmp -- len ) bdim * pixels bdata ;
: bsize ( bmp -- len ) bdim * pixels bdata ;


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


=={{header|Fortran}}==
=={{header|Fortran}}==
Line 1,082: Line 1,082:
(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]])


<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,123: Line 1,123:
end if
end if


end subroutine read_ppm</lang>
end subroutine read_ppm</syntaxhighlight>


'''Notes''':
'''Notes''':
Line 1,131: Line 1,131:


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


import (
import (
Line 1,198: Line 1,198:
}
}
return b, f.Close()
return b, f.Close()
}</lang>
}</syntaxhighlight>
Demonstration program, also demonstrating functions from task [[Grayscale image]]:
Demonstration program, also demonstrating functions from task [[Grayscale image]]:
<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,227: Line 1,227:
fmt.Println(err)
fmt.Println(err)
}
}
}</lang>
}</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]].
<lang haskell>import Bitmap
<syntaxhighlight lang=haskell>import Bitmap
import Bitmap.RGB
import Bitmap.RGB
import Bitmap.Gray
import Bitmap.Gray
Line 1,242: Line 1,242:
(readNetpbm "original.ppm" :: IO (Image RealWorld RGB)) >>=
(readNetpbm "original.ppm" :: IO (Image RealWorld RGB)) >>=
stToIO . toGrayImage >>=
stToIO . toGrayImage >>=
writeNetpbm "new.pgm"</lang>
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:
<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"</lang>
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]].
<lang j>require 'files'
<syntaxhighlight lang=j>require 'files'


readppm=: monad define
readppm=: monad define
Line 1,261: Line 1,261:
if. (_99 0 +./@e. wbyh,maxval) +. 'P6' -.@-: 2{.t do. _1 return. end.
if. (_99 0 +./@e. wbyh,maxval) +. 'P6' -.@-: 2{.t do. _1 return. end.
(a. i. dat) makeRGB |.wbyh NB. convert to basic bitmap format
(a. i. dat) makeRGB |.wbyh NB. convert to basic bitmap format
)</lang>
)</syntaxhighlight>


'''Example:'''<br>
'''Example:'''<br>
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.
<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'</lang>
myimgGray writeppm jpath '~temp/myimgGray.ppm'</syntaxhighlight>


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


<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)</lang>
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.
<lang scala>// Version 1.2.40
<syntaxhighlight lang=scala>// Version 1.2.40


import java.awt.Color
import java.awt.Color
Line 1,410: Line 1,410:
}
}
}
}
}</lang>
}</syntaxhighlight>


=={{header|Lua}}==
=={{header|Lua}}==
<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,446: Line 1,446:
return image
return image
end</lang>
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.


<lang M2000 Interpreter>
<syntaxhighlight lang=M2000 Interpreter>
Module Checkit {
Module Checkit {
Function Bitmap {
Function Bitmap {
Line 1,622: Line 1,622:
Checkit
Checkit


</syntaxhighlight>
</lang>


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


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


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


<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,760: Line 1,760:
r_channel,
r_channel,
g_channel,
g_channel,
b_channel)</lang>
b_channel)</syntaxhighlight>


and converting a given color file to grayscale:
and converting a given color file to grayscale:
<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
output_ppm ~oc:stdout ~img;
output_ppm ~oc:stdout ~img;
;;</lang>
;;</syntaxhighlight>
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 -
Line 1,773: Line 1,773:
=={{header|Oz}}==
=={{header|Oz}}==
The read function in module <code>"BitmapIO.oz"</code>:
The read function in module <code>"BitmapIO.oz"</code>:
<lang oz>functor
<syntaxhighlight lang=oz>functor
import
import
Bitmap
Bitmap
Line 1,856: Line 1,856:


%% Omitted: Write
%% Omitted: Write
end</lang>
end</syntaxhighlight>


The actual task:
The actual task:
<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,865: Line 1,865:
G = {Grayscale.toGraymap B}
G = {Grayscale.toGraymap B}
in
in
{BitmapIO.write {Grayscale.fromGraymap G} "greyimage.ppm"}</lang>
{BitmapIO.write {Grayscale.fromGraymap G} "greyimage.ppm"}</syntaxhighlight>


=={{header|Perl}}==
=={{header|Perl}}==
Line 1,871: Line 1,871:
{{libheader|Imlib2}}
{{libheader|Imlib2}}


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


use strict;
use strict;
Line 1,884: Line 1,884:
$img->save("out1.png");
$img->save("out1.png");


exit 0;</lang>
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
<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,920: Line 1,920:
sequence img = read_ppm("Lena.ppm")
sequence img = read_ppm("Lena.ppm")
img = to_grey(img)
img = to_grey(img)
write_ppm("LenaGray.ppm",img)</lang>
write_ppm("LenaGray.ppm",img)</syntaxhighlight>


=={{header|PicoLisp}}==
=={{header|PicoLisp}}==
<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,940: Line 1,940:
(map
(map
'((X) (set X (list (rd 1) (rd 1) (rd 1))))
'((X) (set X (list (rd 1) (rd 1) (rd 1))))
Y ) ) ) ) ) )</lang>
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":
<lang PicoLisp>(pgmWrite (ppm->pgm (ppmRead "img.ppm")) "img.pgm")</lang>
<syntaxhighlight lang=PicoLisp>(pgmWrite (ppm->pgm (ppmRead "img.ppm")) "img.pgm")</syntaxhighlight>


=={{header|PL/I}}==
=={{header|PL/I}}==
<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,009: Line 2,009:
return (index('0123456789', ch) > 0);
return (index('0123456789', ch) > 0);
end is_digit;
end is_digit;
end test;</lang>
end test;</syntaxhighlight>


=={{header|PureBasic}}==
=={{header|PureBasic}}==
<lang PureBasic>Structure PPMColor
<syntaxhighlight lang=PureBasic>Structure PPMColor
r.c
r.c
g.c
g.c
Line 2,069: Line 2,069:
EndIf
EndIf
EndIf
EndIf
EndProcedure</lang>
EndProcedure</syntaxhighlight>


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]]
<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,079: Line 2,079:
file2 = Left(file, Len(file) - Len(GetExtensionPart(file))) + "_grayscale." + GetExtensionPart(file)
file2 = Left(file, Len(file) - Len(GetExtensionPart(file))) + "_grayscale." + GetExtensionPart(file)
SaveImageAsPPM(image, file2, 1)
SaveImageAsPPM(image, file2, 1)
EndIf</lang>
EndIf</syntaxhighlight>


=={{header|Python}}==
=={{header|Python}}==
Line 2,085: Line 2,085:


Extending the example given [[Basic_bitmap_storage#Alternative_version|here]]
Extending the example given [[Basic_bitmap_storage#Alternative_version|here]]
<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,153: Line 2,153:
4 4 4 0 0 0 0 0 0 0 0 0
4 4 4 0 0 0 0 0 0 0 0 0


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


=={{header|Racket}}==
=={{header|Racket}}==
<lang racket>
<syntaxhighlight lang=racket>
#lang racket
#lang racket
(require racket/draw)
(require racket/draw)
Line 2,179: Line 2,179:
(send dc draw-point x y)))
(send dc draw-point x y)))
bm))
bm))
</syntaxhighlight>
</lang>


=={{header|Raku}}==
=={{header|Raku}}==
Line 2,186: Line 2,186:
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.


<lang perl6>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,221: Line 2,221:
grayscale($b);
grayscale($b);


'./camelia-gs.pgm'.IO.open(:bin, :w).write: $b.P5;</lang>
'./camelia-gs.pgm'.IO.open(:bin, :w).write: $b.P5;</syntaxhighlight>


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).
Line 2,230: Line 2,230:


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.
<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,265: Line 2,265:


call charout oFID /*close the output file just to be safe*/
call charout oFID /*close the output file just to be safe*/
say 'File ' oFID " was created." /*stick a fork in it, we're all done. */</lang>
say 'File ' oFID " was created." /*stick a fork in it, we're all done. */</syntaxhighlight>
{{out|output}}
{{out|output}}
<pre>
<pre>
Line 2,273: Line 2,273:
=={{header|Ruby}}==
=={{header|Ruby}}==
Extending [[Basic_bitmap_storage#Ruby]]
Extending [[Basic_bitmap_storage#Ruby]]
<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,305: Line 2,305:


# then, convert to grayscale
# then, convert to grayscale
Pixmap.open('testcross.ppm').to_grayscale!.save('testgray.ppm')</lang>
Pixmap.open('testcross.ppm').to_grayscale!.save('testgray.ppm')</syntaxhighlight>


=={{header|Rust}}==
=={{header|Rust}}==
<lang rust>
<syntaxhighlight lang=rust>
parser.rs:
parser.rs:
use super::{Color, ImageFormat};
use super::{Color, ImageFormat};
Line 2,591: Line 2,591:
println!("Dimensions: {} x {}", image.height, image.width);
println!("Dimensions: {} x {}", image.height, image.width);
}
}
</syntaxhighlight>
</lang>




Line 2,599: Line 2,599:
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.


<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,644: Line 2,644:
out
out
}
}
}</lang>
}</syntaxhighlight>


Usage:
Usage:
<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,661: Line 2,661:
}
}
}
}
}</lang>
}</syntaxhighlight>


=={{header|Seed7}}==
=={{header|Seed7}}==
<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,699: Line 2,699:
close(ppmFile);
close(ppmFile);
end if;
end if;
end func;</lang>
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:
<lang tcl>package require Tk
<syntaxhighlight lang=tcl>package require Tk


proc readPPM {image file} {
proc readPPM {image file} {
$image read $file -format ppm
$image read $file -format ppm
}</lang>
}</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:
<lang tcl>package require Tk
<syntaxhighlight lang=tcl>package require Tk


proc grayscaleFile {filename {newFilename ""}} {
proc grayscaleFile {filename {newFilename ""}} {
Line 2,730: Line 2,730:
image delete $buffer
image delete $buffer
}
}
}</lang>
}</syntaxhighlight>


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:
<lang tcl>package require Tk
<syntaxhighlight lang=tcl>package require Tk


proc grayscaleFile {filename {newFilename ""}} {
proc grayscaleFile {filename {newFilename ""}} {
Line 2,744: Line 2,744:
image delete $buffer
image delete $buffer
}
}
}</lang>
}</syntaxhighlight>


=={{header|UNIX Shell}}==
=={{header|UNIX Shell}}==
Line 2,751: Line 2,751:


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


Add the following function to the <tt>Bitmap_t</tt> type
Add the following function to the <tt>Bitmap_t</tt> type
<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,802: Line 2,802:
fi
fi
exec 4<&-
exec 4<&-
}</lang>
}</syntaxhighlight>


Now we can:
Now we can:
<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,817: Line 2,817:
c.grayscale
c.grayscale
c.to_s
c.to_s
c.write "$HOME/tmp/bitmap_g.ppm"</lang>
c.write "$HOME/tmp/bitmap_g.ppm"</syntaxhighlight>


=={{header|Vedit macro language}}==
=={{header|Vedit macro language}}==
<lang vedit>// Load a PPM file
<syntaxhighlight lang=vedit>// Load a PPM file
// @10 = filename
// @10 = filename
// On return:
// On return:
Line 2,836: Line 2,836:
Search("|X", ADVANCE) // skip maxval (assume 255)
Search("|X", ADVANCE) // skip maxval (assume 255)
Del_Block(0,CP) // remove the header
Del_Block(0,CP) // remove the header
Return</lang>
Return</syntaxhighlight>


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]].
<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,857: Line 2,857:
// Cleanup and exit
// Cleanup and exit
Buf_Switch(#20) Buf_Quit(OK)
Buf_Switch(#20) Buf_Quit(OK)
return</lang>
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.
<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,936: Line 2,936:
}
}


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


=={{header|XPL0}}==
=={{header|XPL0}}==
Line 2,943: Line 2,943:
files larger than 1280x1024 are clipped to the screen dimensions.
files larger than 1280x1024 are clipped to the screen dimensions.


<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,987: Line 2,987:
X:= ChIn(1); \wait for keystroke
X:= ChIn(1); \wait for keystroke
SetVid(3); \restore normal text display
SetVid(3); \restore normal text display
]</lang>
]</syntaxhighlight>


=={{header|Yabasic}}==
=={{header|Yabasic}}==
<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,016: Line 3,016:
return true
return true
end sub</lang>
end sub</syntaxhighlight>


=={{header|zkl}}==
=={{header|zkl}}==
Line 3,024: Line 3,024:
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]]
<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,034: Line 3,034:
}
}


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