Bitmap/Read a PPM file: Difference between revisions

m
syntax highlighting fixup automation
(Added solution for Action!)
m (syntax highlighting fixup automation)
Line 10:
{{trans|Python}}
 
<langsyntaxhighlight lang=11l>T Colour
Byte r, g, b
 
Line 107:
print(‘Grey PPM:’)
bitmap.togreyscale()
print(bitmap.writeppmp3())</langsyntaxhighlight>
 
{{out}}
Line 126:
{{libheader|Action! Bitmap tools}}
{{libheader|Action! Tool Kit}}
<langsyntaxhighlight lang=Action!>INCLUDE "H6:RGB2GRAY.ACT" ;from task Grayscale image
 
PROC DecodeSize(CHAR ARRAY s BYTE POINTER width,height)
Line 261:
PrintF("Loading %S...%E%E",path2)
Load(path2)
RETURN</langsyntaxhighlight>
{{out}}
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Read_a_PPM_file.png Screenshot from Atari 8-bit computer]
Line 283:
 
=={{header|Ada}}==
<langsyntaxhighlight lang=ada>with Ada.Characters.Latin_1; use Ada.Characters.Latin_1;
with Ada.Integer_Text_IO; use Ada.Integer_Text_IO;
with Ada.Streams.Stream_IO; use Ada.Streams.Stream_IO;
Line 352:
return Result;
end;
end Get_PPM;</langsyntaxhighlight>
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.
<langsyntaxhighlight lang=ada>declare
F1, F2 : File_Type;
begin
Line 362:
Close (F1);
Close (F2);
end;</langsyntaxhighlight>
 
=={{header|AutoHotkey}}==
Line 368:
Only ppm6 files supported.
 
<langsyntaxhighlight lang=AutoHotkey>img := ppm_read("lena50.ppm") ;
x := img[4,4] ; get pixel(4,4)
y := img[24,24] ; get pixel(24,24)
Line 424:
return bitmap
}
#include bitmap_storage.ahk ; from http://rosettacode.org/wiki/Basic_bitmap_storage/AutoHotkey</langsyntaxhighlight>
 
=={{header|BBC BASIC}}==
{{works with|BBC BASIC for Windows}}
<langsyntaxhighlight lang=bbcbasic> f% = OPENIN("c:\lena.ppm")
IF f%=0 ERROR 100, "Failed to open input file"
Line 457:
GCOL 1
LINE x%*2,y%*2,x%*2,y%*2
ENDPROC</langsyntaxhighlight>
 
=={{header|C}}==
Line 465:
Interface:
 
<syntaxhighlight lang =c>image get_ppm(FILE *pf);</langsyntaxhighlight>
 
Implementation:
 
<langsyntaxhighlight lang=c>#include "imglib.h"
 
#define PPMREADBUFLEN 256
Line 506:
return img;
}
}</langsyntaxhighlight>
 
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):
 
<langsyntaxhighlight lang=c>#include <stdio.h>
#include "imglib.h"
 
Line 525:
free_img(source); free_img((image)idest);
return 0;
}</langsyntaxhighlight>
 
=={{header|C sharp|C#}}==
Tested with [[Write ppm file#C.23|this solution.]]
 
<langsyntaxhighlight lang=csharp>using System.IO;
class PPMReader
{
Line 562:
return bitmap;
}
}</langsyntaxhighlight>
 
=={{header|Common Lisp}}==
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.
 
<langsyntaxhighlight lang=lisp>
(in-package #:rgb-pixel-buffer)
 
Line 640:
 
(export 'read-ppm-image)
</syntaxhighlight>
</lang>
To read the feep.ppm file as shown on the description page for the ppm format use:
<langsyntaxhighlight lang=lisp>
(read-ppm-image "feep.ppm")
</syntaxhighlight>
</lang>
 
=={{header|D}}==
Line 652:
Class helper for read and write Bitmap's and Ppm's
{{Trans|C#}}
<langsyntaxhighlight lang=Delphi>
program BtmAndPpm;
 
Line 780:
end;
end.
</syntaxhighlight>
</lang>
 
=={{header|E}}==
 
<langsyntaxhighlight lang=e>def chr := <import:java.lang.makeCharacter>.asChar
 
def readPPM(inputStream) {
Line 838:
image.replace(data.snapshot())
return image
}</langsyntaxhighlight>
 
[[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.
 
<langsyntaxhighlight lang=e>def readPPMTask(inputFile, outputFile) {
makeGrayscale \
.fromColor(readPPM(<import:java.io.makeFileInputStream>(inputFile))) \
.toColor() \
.writePPM(<import:java.io.makeFileOutputStream>(outputFile))
}</langsyntaxhighlight>
 
=={{header|Erlang}}==
 
<langsyntaxhighlight lang=erlang>
% This module provides basic operations on ppm files:
% Read from file, create ppm in memory (from generic bitmap) and save to file.
Line 954:
encode_decimal(Number) ->
integer_to_list(Number).
</syntaxhighlight>
</lang>
 
Usage in accordance with Grayscale Task:
<langsyntaxhighlight lang=erlang>
Colorful = ppm:read("colorful.ppm"),
Gray = ros_bitmap:convert(ros_bitmap:convert(Colorful, grey), rgb),
ppm:write(Gray, "gray.ppm"),
</syntaxhighlight>
</lang>
 
=={{header|Euphoria}}==
<langsyntaxhighlight lang=euphoria>include get.e
 
function get2(integer fn)
Line 1,004:
close(fn)
return image
end function</langsyntaxhighlight>
 
Converting an image to grayscale:
<langsyntaxhighlight lang=euphoria>sequence image
image = read_ppm("image.ppm")
image = to_gray(image)
image = to_color(image)
write_ppm("image_gray.ppm",image)</langsyntaxhighlight>
 
=={{header|FBSL}}==
Line 1,018:
'''24-bpp P6 PPM solution:'''
[[File:FBSLLena.png|right]]
<langsyntaxhighlight lang=qbasic>#ESCAPECHARS ON
 
DIM colored = ".\\Lena.ppm", grayscale = ".\\LenaGry.ppm"
Line 1,035:
NEXT
 
FILEPUT(FILEOPEN(grayscale, BINARY_NEW), FILEGET): FILECLOSE(FILEOPEN) ' Save buffer</langsyntaxhighlight>
 
=={{header|Forth}}==
<langsyntaxhighlight lang=forth>: read-ppm { fid -- bmp }
pad dup 80 fid read-line throw 0= abort" Partial line"
s" P6" compare abort" Only P6 supported."
Line 1,075:
: bsize ( bmp -- len ) bdim * pixels bdata ;
 
test dup bsize test2 dup bsize compare . \ 0 if identical</langsyntaxhighlight>
 
=={{header|Fortran}}==
Line 1,082:
(This function is part of module RCImageIO, see [[Write ppm file#Fortran|Write ppm file]])
 
<langsyntaxhighlight lang=fortran>subroutine read_ppm(u, img)
integer, intent(in) :: u
type(rgbimage), intent(out) :: img
Line 1,123:
end if
 
end subroutine read_ppm</langsyntaxhighlight>
 
'''Notes''':
Line 1,131:
 
=={{header|Go}}==
<langsyntaxhighlight lang=go>package raster
 
import (
Line 1,198:
}
return b, f.Close()
}</langsyntaxhighlight>
Demonstration program, also demonstrating functions from task [[Grayscale image]]:
<langsyntaxhighlight lang=go>package main
 
// Files required to build supporting package raster are found in:
Line 1,227:
fmt.Println(err)
}
}</langsyntaxhighlight>
 
=={{header|Haskell}}==
The definition of <tt>Bitmap.Netpbm.readNetpbm</tt> is given [[Write ppm file|here]].
<langsyntaxhighlight lang=haskell>import Bitmap
import Bitmap.RGB
import Bitmap.Gray
Line 1,242:
(readNetpbm "original.ppm" :: IO (Image RealWorld RGB)) >>=
stToIO . toGrayImage >>=
writeNetpbm "new.pgm"</langsyntaxhighlight>
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:
<langsyntaxhighlight lang=haskell>main =
(readNetpbm "original.ppm" :: IO (Image RealWorld RGB)) >>=
stToIO . (toRGBImage <=< toGrayImage) >>=
writeNetpbm "new.ppm"</langsyntaxhighlight>
 
=={{header|J}}==
'''Solution:'''<br>
Uses <tt>makeRGB</tt> from [[Basic bitmap storage#J|Basic bitmap storage]].
<langsyntaxhighlight lang=j>require 'files'
 
readppm=: monad define
Line 1,261:
if. (_99 0 +./@e. wbyh,maxval) +. 'P6' -.@-: 2{.t do. _1 return. end.
(a. i. dat) makeRGB |.wbyh NB. convert to basic bitmap format
)</langsyntaxhighlight>
 
'''Example:'''<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.
<langsyntaxhighlight lang=j>myimg=: readppm jpath '~temp/myimg.ppm'
myimgGray=: toColor toGray myimg
myimgGray writeppm jpath '~temp/myimgGray.ppm'</langsyntaxhighlight>
 
=={{header|Julia}}==
{{works with|Julia|0.6}}
 
<langsyntaxhighlight lang=julia>using Images, FileIO, Netpbm
 
rgbimg = load("data/bitmapInputTest.ppm")
greyimg = Gray.(rgbimg)
save("data/bitmapOutputTest.ppm", greyimg)</langsyntaxhighlight>
 
=={{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.
<langsyntaxhighlight lang=scala>// Version 1.2.40
 
import java.awt.Color
Line 1,410:
}
}
}</langsyntaxhighlight>
 
=={{header|Lua}}==
<langsyntaxhighlight lang=lua>function Read_PPM( filename )
local fp = io.open( filename, "rb" )
if fp == nil then return nil end
Line 1,446:
return image
end</langsyntaxhighlight>
 
=={{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.
 
<langsyntaxhighlight lang=M2000 Interpreter>
Module Checkit {
Function Bitmap {
Line 1,622:
Checkit
 
</syntaxhighlight>
</lang>
 
=={{header|Mathematica}}/ {{header|Wolfram Language}}==
<langsyntaxhighlight lang=Mathematica>Import["file.ppm","PPM"]
</syntaxhighlight>
</lang>
 
=={{header|Nim}}==
<langsyntaxhighlight lang=nim>import strutils
import bitmap
import streams
Line 1,719:
when isMainModule:
let image = readPPM("output.ppm")
echo image.h, " ", image.w</langsyntaxhighlight>
 
=={{header|OCaml}}==
 
<langsyntaxhighlight lang=ocaml>let read_ppm ~filename =
let ic = open_in filename in
let line = input_line ic in
Line 1,760:
r_channel,
g_channel,
b_channel)</langsyntaxhighlight>
 
and converting a given color file to grayscale:
<langsyntaxhighlight lang=ocaml>let () =
let img = read_ppm ~filename:"logo.ppm" in
let img = to_color(to_grayscale ~img) in
output_ppm ~oc:stdout ~img;
;;</langsyntaxhighlight>
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 -
Line 1,773:
=={{header|Oz}}==
The read function in module <code>"BitmapIO.oz"</code>:
<langsyntaxhighlight lang=oz>functor
import
Bitmap
Line 1,856:
 
%% Omitted: Write
end</langsyntaxhighlight>
 
The actual task:
<langsyntaxhighlight lang=oz>declare
[BitmapIO Grayscale] = {Module.link ['BitmapIO.ozf' 'Grayscale.ozf']}
 
Line 1,865:
G = {Grayscale.toGraymap B}
in
{BitmapIO.write {Grayscale.fromGraymap G} "greyimage.ppm"}</langsyntaxhighlight>
 
=={{header|Perl}}==
Line 1,871:
{{libheader|Imlib2}}
 
<langsyntaxhighlight lang=perl>#! /usr/bin/perl
 
use strict;
Line 1,884:
$img->save("out1.png");
 
exit 0;</langsyntaxhighlight>
 
=={{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>
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
<langsyntaxhighlight lang=Phix>-- demo\rosetta\Bitmap_read_ppm.exw (runnable version)
 
function read_ppm(string filename)
Line 1,920:
sequence img = read_ppm("Lena.ppm")
img = to_grey(img)
write_ppm("LenaGray.ppm",img)</langsyntaxhighlight>
 
=={{header|PicoLisp}}==
<langsyntaxhighlight lang=PicoLisp>(de ppmRead (File)
(in File
(unless (and `(hex "5036") (rd 2)) # P6
Line 1,940:
(map
'((X) (set X (list (rd 1) (rd 1) (rd 1))))
Y ) ) ) ) ) )</langsyntaxhighlight>
Read a color image "img.ppm", convert and write to "img.pgm":
<langsyntaxhighlight lang=PicoLisp>(pgmWrite (ppm->pgm (ppmRead "img.ppm")) "img.pgm")</langsyntaxhighlight>
 
=={{header|PL/I}}==
<langsyntaxhighlight lang=PL/I>
/* BITMAP FILE: read in a file in PPM format, P6 (binary). 14/5/2010 */
test: procedure options (main);
Line 2,009:
return (index('0123456789', ch) > 0);
end is_digit;
end test;</langsyntaxhighlight>
 
=={{header|PureBasic}}==
<langsyntaxhighlight lang=PureBasic>Structure PPMColor
r.c
g.c
Line 2,069:
EndIf
EndIf
EndProcedure</langsyntaxhighlight>
 
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]]
<langsyntaxhighlight lang=PureBasic>Define file.s, file2.s, image = 3
file = OpenFileRequester("Select source image file", "", "PPM image (*.ppm)|*.ppm", 0)
If file And LCase(GetExtensionPart(file)) = "ppm"
Line 2,079:
file2 = Left(file, Len(file) - Len(GetExtensionPart(file))) + "_grayscale." + GetExtensionPart(file)
SaveImageAsPPM(image, file2, 1)
EndIf</langsyntaxhighlight>
 
=={{header|Python}}==
Line 2,085:
 
Extending the example given [[Basic_bitmap_storage#Alternative_version|here]]
<langsyntaxhighlight lang=python># With help from http://netpbm.sourceforge.net/doc/ppm.html
 
# String masquerading as ppm file (version P3)
Line 2,153:
4 4 4 0 0 0 0 0 0 0 0 0
 
'''</langsyntaxhighlight>
 
=={{header|Racket}}==
<langsyntaxhighlight lang=racket>
#lang racket
(require racket/draw)
Line 2,179:
(send dc draw-point x y)))
bm))
</syntaxhighlight>
</lang>
 
=={{header|Raku}}==
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.
 
<syntaxhighlight lang=raku perl6line>class Pixel { has UInt ($.R, $.G, $.B) }
class Bitmap {
has UInt ($.width, $.height);
Line 2,221:
grayscale($b);
 
'./camelia-gs.pgm'.IO.open(:bin, :w).write: $b.P5;</langsyntaxhighlight>
 
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:
 
This REXX program handles alternative delimiters as well as comments within the PPM header.
<langsyntaxhighlight 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.*/
if iFN=='' | iFN=="," then iFN= 'Lenna50' /*Not specified? Then use the default.*/
Line 2,265:
 
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. */</langsyntaxhighlight>
{{out|output}}
<pre>
Line 2,273:
=={{header|Ruby}}==
Extending [[Basic_bitmap_storage#Ruby]]
<langsyntaxhighlight lang=ruby>class Pixmap
# 'open' is a class method
def self.open(filename)
Line 2,305:
 
# then, convert to grayscale
Pixmap.open('testcross.ppm').to_grayscale!.save('testgray.ppm')</langsyntaxhighlight>
 
=={{header|Rust}}==
<langsyntaxhighlight lang=rust>
parser.rs:
use super::{Color, ImageFormat};
Line 2,591:
println!("Dimensions: {} x {}", image.height, image.width);
}
</syntaxhighlight>
</lang>
 
 
Line 2,599:
See also Task [[Write_ppm_file#Scala|Write a PPM File]] for save code.
 
<langsyntaxhighlight lang=scala>import scala.io._
import scala.swing._
import java.io._
Line 2,644:
out
}
}</langsyntaxhighlight>
 
Usage:
<langsyntaxhighlight lang=scala>object PixmapTest {
def main(args: Array[String]): Unit = {
val img=Pixmap.load("image.ppm").get
Line 2,661:
}
}
}</langsyntaxhighlight>
 
=={{header|Seed7}}==
<langsyntaxhighlight lang=seed7>$ include "seed7_05.s7i";
include "draw.s7i";
include "color.s7i";
Line 2,699:
close(ppmFile);
end if;
end func;</langsyntaxhighlight>
 
=={{header|Tcl}}==
{{libheader|Tk}}
The actual PPM reader is built into the photo image engine:
<langsyntaxhighlight lang=tcl>package require Tk
 
proc readPPM {image file} {
$image read $file -format ppm
}</langsyntaxhighlight>
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:
<langsyntaxhighlight lang=tcl>package require Tk
 
proc grayscaleFile {filename {newFilename ""}} {
Line 2,730:
image delete $buffer
}
}</langsyntaxhighlight>
 
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:
<langsyntaxhighlight lang=tcl>package require Tk
 
proc grayscaleFile {filename {newFilename ""}} {
Line 2,744:
image delete $buffer
}
}</langsyntaxhighlight>
 
=={{header|UNIX Shell}}==
Line 2,751:
 
Add the following functions to the <tt>RGBColor_t</tt> type
<langsyntaxhighlight lang=bash> function setrgb {
_.r=$1
_.g=$2
Line 2,761:
_.g=$x
_.b=$x
}</langsyntaxhighlight>
 
Add the following function to the <tt>Bitmap_t</tt> type
<langsyntaxhighlight lang=bash> function grayscale {
RGBColor_t c
for ((y=0; y<_.height; y++)); do
Line 2,802:
fi
exec 4<&-
}</langsyntaxhighlight>
 
Now we can:
<langsyntaxhighlight lang=bash>Bitmap_t c
c.read "$HOME/tmp/bitmap.ppm"
c.to_s
Line 2,817:
c.grayscale
c.to_s
c.write "$HOME/tmp/bitmap_g.ppm"</langsyntaxhighlight>
 
=={{header|Vedit macro language}}==
<langsyntaxhighlight lang=vedit>// Load a PPM file
// @10 = filename
// On return:
Line 2,836:
Search("|X", ADVANCE) // skip maxval (assume 255)
Del_Block(0,CP) // remove the header
Return</langsyntaxhighlight>
 
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]].
<langsyntaxhighlight lang=vedit>// Load RGB image
Reg_Set(10, "|(USER_MACRO)\example.ppm")
Call("LOAD_PPM")
Line 2,857:
// Cleanup and exit
Buf_Switch(#20) Buf_Quit(OK)
return</langsyntaxhighlight>
 
=={{header|Wren}}==
{{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.
<langsyntaxhighlight lang=ecmascript>import "graphics" for Canvas, ImageData, Color
import "dome" for Window, Process
import "io" for FileSystem
Line 2,936:
}
 
var Game = Bitmap.new("Lenna100.ppm", "Lenna100_gs.jpg", 1048, 512)</langsyntaxhighlight>
 
=={{header|XPL0}}==
Line 2,943:
files larger than 1280x1024 are clipped to the screen dimensions.
 
<langsyntaxhighlight lang=XPL0>include c:\cxpl\codes; \intrinsic 'code' declarations
 
func OpenInFile; \Open for input the file typed on command line
Line 2,987:
X:= ChIn(1); \wait for keystroke
SetVid(3); \restore normal text display
]</langsyntaxhighlight>
 
=={{header|Yabasic}}==
<langsyntaxhighlight lang=Yabasic>sub readPPM(f$)
local ff, x, y, t$, dcol$, wid, hei
 
Line 3,016:
return true
end sub</langsyntaxhighlight>
 
=={{header|zkl}}==
Line 3,024:
I used a slightly different image from what is shown, but the results are the same.
[[File:FBSLLena.png|right]]
<langsyntaxhighlight lang=zkl>//24-bpp P6 PPM solution:
image:=File("lena.ppm","rb").read();
start:=image.find("\n255\n")+5; // Get sizeof PPM header
Line 3,034:
}
 
File("lenaGrey.ppm","wb").write(image);</langsyntaxhighlight>
 
 
10,333

edits