Bitmap/Read a PPM file: Difference between revisions

m
Automated syntax highlighting fixup (second round - minor fixes)
m (syntax highlighting fixup automation)
m (Automated syntax highlighting fixup (second round - minor fixes))
Line 1:
[[Category:Input Output]]
[[Category:E examples needing attention]]
{{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).
Line 6 ⟶ 7:
 
'''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}}==
{{trans|Python}}
 
<syntaxhighlight lang="11l">T Colour
Byte r, g, b
 
Line 121:
4 4 4 0 0 0 0 0 0 0 0 0
</pre>
 
=={{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].
{{libheader|Action! Bitmap tools}}
{{libheader|Action! Tool Kit}}
<syntaxhighlight lang=Action"action!">INCLUDE "H6:RGB2GRAY.ACT" ;from task Grayscale image
 
PROC DecodeSize(CHAR ARRAY s BYTE POINTER width,height)
Line 281 ⟶ 280:
45 54 74
</pre>
 
=={{header|Ada}}==
<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.Streams.Stream_IO; use Ada.Streams.Stream_IO;
Line 354 ⟶ 352:
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.
<syntaxhighlight lang="ada">declare
F1, F2 : File_Type;
begin
Line 363 ⟶ 361:
Close (F2);
end;</syntaxhighlight>
 
=={{header|AutoHotkey}}==
{{works with | AutoHotkey_L}}
Only ppm6 files supported.
 
<syntaxhighlight lang=AutoHotkey"autohotkey">img := ppm_read("lena50.ppm") ;
x := img[4,4] ; get pixel(4,4)
y := img[24,24] ; get pixel(24,24)
Line 425 ⟶ 422:
}
#include bitmap_storage.ahk ; from http://rosettacode.org/wiki/Basic_bitmap_storage/AutoHotkey</syntaxhighlight>
 
=={{header|BBC BASIC}}==
{{works with|BBC BASIC for Windows}}
<syntaxhighlight lang="bbcbasic"> f% = OPENIN("c:\lena.ppm")
IF f%=0 ERROR 100, "Failed to open input file"
Line 458 ⟶ 454:
LINE x%*2,y%*2,x%*2,y%*2
ENDPROC</syntaxhighlight>
 
=={{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
Line 465 ⟶ 460:
Interface:
 
<syntaxhighlight lang="c">image get_ppm(FILE *pf);</syntaxhighlight>
 
Implementation:
 
<syntaxhighlight lang="c">#include "imglib.h"
 
#define PPMREADBUFLEN 256
Line 510 ⟶ 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):
 
<syntaxhighlight lang="c">#include <stdio.h>
#include "imglib.h"
 
Line 526 ⟶ 521:
return 0;
}</syntaxhighlight>
 
=={{header|C sharp|C#}}==
Tested with [[Write ppm file#C.23|this solution.]]
 
<syntaxhighlight lang="csharp">using System.IO;
class PPMReader
{
Line 563 ⟶ 557:
}
}</syntaxhighlight>
 
=={{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.
 
<syntaxhighlight lang="lisp">
(in-package #:rgb-pixel-buffer)
 
Line 642 ⟶ 635:
</syntaxhighlight>
To read the feep.ppm file as shown on the description page for the ppm format use:
<syntaxhighlight lang="lisp">
(read-ppm-image "feep.ppm")
</syntaxhighlight>
 
=={{header|D}}==
The Image module contains a loadPPM6 function to load binary PPM images.
 
=={{header|Delphi}}==
Class helper for read and write Bitmap's and Ppm's
{{Trans|C#}}
<syntaxhighlight lang=Delphi"delphi">
program BtmAndPpm;
 
Line 781 ⟶ 772:
end.
</syntaxhighlight>
 
=={{header|E}}==
 
<syntaxhighlight lang="e">def chr := <import:java.lang.makeCharacter>.asChar
 
def readPPM(inputStream) {
Line 840 ⟶ 830:
}</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.
 
<syntaxhighlight lang="e">def readPPMTask(inputFile, outputFile) {
makeGrayscale \
.fromColor(readPPM(<import:java.io.makeFileInputStream>(inputFile))) \
Line 848 ⟶ 838:
.writePPM(<import:java.io.makeFileOutputStream>(outputFile))
}</syntaxhighlight>
 
=={{header|Erlang}}==
 
<syntaxhighlight 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 957 ⟶ 946:
 
Usage in accordance with Grayscale Task:
<syntaxhighlight lang="erlang">
Colorful = ppm:read("colorful.ppm"),
Gray = ros_bitmap:convert(ros_bitmap:convert(Colorful, grey), rgb),
ppm:write(Gray, "gray.ppm"),
</syntaxhighlight>
 
=={{header|Euphoria}}==
<syntaxhighlight lang="euphoria">include get.e
 
function get2(integer fn)
Line 1,007 ⟶ 995:
 
Converting an image to grayscale:
<syntaxhighlight lang="euphoria">sequence image
image = read_ppm("image.ppm")
image = to_gray(image)
image = to_color(image)
write_ppm("image_gray.ppm",image)</syntaxhighlight>
 
=={{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.
Line 1,018 ⟶ 1,005:
'''24-bpp P6 PPM solution:'''
[[File:FBSLLena.png|right]]
<syntaxhighlight lang="qbasic">#ESCAPECHARS ON
 
DIM colored = ".\\Lena.ppm", grayscale = ".\\LenaGry.ppm"
Line 1,036 ⟶ 1,023:
 
FILEPUT(FILEOPEN(grayscale, BINARY_NEW), FILEGET): FILECLOSE(FILEOPEN) ' Save buffer</syntaxhighlight>
 
=={{header|Forth}}==
<syntaxhighlight 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,076 ⟶ 1,062:
 
test dup bsize test2 dup bsize compare . \ 0 if identical</syntaxhighlight>
 
=={{header|Fortran}}==
{{works with|Fortran|90 and later}}
Line 1,082 ⟶ 1,067:
(This function is part of module RCImageIO, see [[Write ppm file#Fortran|Write ppm file]])
 
<syntaxhighlight lang="fortran">subroutine read_ppm(u, img)
integer, intent(in) :: u
type(rgbimage), intent(out) :: img
Line 1,129 ⟶ 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.
* comments after the first line are not handled
 
=={{header|Go}}==
<syntaxhighlight lang="go">package raster
 
import (
Line 1,200 ⟶ 1,184:
}</syntaxhighlight>
Demonstration program, also demonstrating functions from task [[Grayscale image]]:
<syntaxhighlight lang="go">package main
 
// Files required to build supporting package raster are found in:
Line 1,228 ⟶ 1,212:
}
}</syntaxhighlight>
 
=={{header|Haskell}}==
The definition of <tt>Bitmap.Netpbm.readNetpbm</tt> is given [[Write ppm file|here]].
<syntaxhighlight lang="haskell">import Bitmap
import Bitmap.RGB
import Bitmap.Gray
Line 1,244 ⟶ 1,227:
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:
<syntaxhighlight lang="haskell">main =
(readNetpbm "original.ppm" :: IO (Image RealWorld RGB)) >>=
stToIO . (toRGBImage <=< toGrayImage) >>=
writeNetpbm "new.ppm"</syntaxhighlight>
 
=={{header|J}}==
'''Solution:'''<br>
Uses <tt>makeRGB</tt> from [[Basic bitmap storage#J|Basic bitmap storage]].
<syntaxhighlight lang="j">require 'files'
 
readppm=: monad define
Line 1,266 ⟶ 1,248:
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.
<syntaxhighlight lang="j">myimg=: readppm jpath '~temp/myimg.ppm'
myimgGray=: toColor toGray myimg
myimgGray writeppm jpath '~temp/myimgGray.ppm'</syntaxhighlight>
 
=={{header|Julia}}==
{{works with|Julia|0.6}}
 
<syntaxhighlight lang="julia">using Images, FileIO, Netpbm
 
rgbimg = load("data/bitmapInputTest.ppm")
greyimg = Gray.(rgbimg)
save("data/bitmapOutputTest.ppm", greyimg)</syntaxhighlight>
 
=={{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.
<syntaxhighlight lang="scala">// Version 1.2.40
 
import java.awt.Color
Line 1,411 ⟶ 1,391:
}
}</syntaxhighlight>
 
=={{header|Lua}}==
<syntaxhighlight lang="lua">function Read_PPM( filename )
local fp = io.open( filename, "rb" )
if fp == nil then return nil end
Line 1,447 ⟶ 1,426:
return image
end</syntaxhighlight>
 
=={{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.
 
<syntaxhighlight lang=M2000"m2000 Interpreterinterpreter">
Module Checkit {
Function Bitmap {
Line 1,623 ⟶ 1,601:
 
</syntaxhighlight>
 
=={{header|Mathematica}}/ {{header|Wolfram Language}}==
<syntaxhighlight lang=Mathematica"mathematica">Import["file.ppm","PPM"]
</syntaxhighlight>
 
=={{header|Nim}}==
<syntaxhighlight lang="nim">import strutils
import bitmap
import streams
Line 1,720 ⟶ 1,696:
let image = readPPM("output.ppm")
echo image.h, " ", image.w</syntaxhighlight>
 
=={{header|OCaml}}==
 
<syntaxhighlight lang="ocaml">let read_ppm ~filename =
let ic = open_in filename in
let line = input_line ic in
Line 1,763 ⟶ 1,738:
 
and converting a given color file to grayscale:
<syntaxhighlight lang="ocaml">let () =
let img = read_ppm ~filename:"logo.ppm" in
let img = to_color(to_grayscale ~img) in
Line 1,770 ⟶ 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'':
ocaml script.ml | display -
 
=={{header|Oz}}==
The read function in module <code>"BitmapIO.oz"</code>:
<syntaxhighlight lang="oz">functor
import
Bitmap
Line 1,859 ⟶ 1,833:
 
The actual task:
<syntaxhighlight lang="oz">declare
[BitmapIO Grayscale] = {Module.link ['BitmapIO.ozf' 'Grayscale.ozf']}
 
Line 1,866 ⟶ 1,840:
in
{BitmapIO.write {Grayscale.fromGraymap G} "greyimage.ppm"}</syntaxhighlight>
 
=={{header|Perl}}==
 
{{libheader|Imlib2}}
 
<syntaxhighlight lang="perl">#! /usr/bin/perl
 
use strict;
Line 1,885 ⟶ 1,858:
 
exit 0;</syntaxhighlight>
 
=={{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
<syntaxhighlight lang=Phix"phix">-- demo\rosetta\Bitmap_read_ppm.exw (runnable version)
 
function read_ppm(string filename)
Line 1,921 ⟶ 1,893:
img = to_grey(img)
write_ppm("LenaGray.ppm",img)</syntaxhighlight>
 
=={{header|PicoLisp}}==
<syntaxhighlight lang=PicoLisp"picolisp">(de ppmRead (File)
(in File
(unless (and `(hex "5036") (rd 2)) # P6
Line 1,942 ⟶ 1,913:
Y ) ) ) ) ) )</syntaxhighlight>
Read a color image "img.ppm", convert and write to "img.pgm":
<syntaxhighlight lang=PicoLisp"picolisp">(pgmWrite (ppm->pgm (ppmRead "img.ppm")) "img.pgm")</syntaxhighlight>
 
=={{header|PL/I}}==
<syntaxhighlight lang=PL"pl/Ii">
/* BITMAP FILE: read in a file in PPM format, P6 (binary). 14/5/2010 */
test: procedure options (main);
Line 2,010 ⟶ 1,980:
end is_digit;
end test;</syntaxhighlight>
 
=={{header|PureBasic}}==
<syntaxhighlight lang=PureBasic"purebasic">Structure PPMColor
r.c
g.c
Line 2,072 ⟶ 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]]
<syntaxhighlight lang=PureBasic"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,080 ⟶ 2,049:
SaveImageAsPPM(image, file2, 1)
EndIf</syntaxhighlight>
 
=={{header|Python}}==
{{works with|Python|3.1}}
 
Extending the example given [[Basic_bitmap_storage#Alternative_version|here]]
<syntaxhighlight lang="python"># With help from http://netpbm.sourceforge.net/doc/ppm.html
 
# String masquerading as ppm file (version P3)
Line 2,154 ⟶ 2,122:
 
'''</syntaxhighlight>
 
=={{header|Racket}}==
<syntaxhighlight lang="racket">
#lang racket
(require racket/draw)
Line 2,180 ⟶ 2,147:
bm))
</syntaxhighlight>
 
=={{header|Raku}}==
(formerly Perl 6)
Line 2,186 ⟶ 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.
 
<syntaxhighlight lang="raku" line>class Pixel { has UInt ($.R, $.G, $.B) }
class Bitmap {
has UInt ($.width, $.height);
Line 2,224 ⟶ 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).
 
=={{header|REXX}}==
The input file &nbsp; '''Lenna50.ppm''' &nbsp; is a '''PPM''' format of
Line 2,230 ⟶ 2,195:
 
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. */
parse arg iFN oFN /*obtain optional argument from the CL.*/
if iFN=='' | iFN=="," then iFN= 'Lenna50' /*Not specified? Then use the default.*/
Line 2,270 ⟶ 2,235:
File greyscale.ppm was created.
</pre>
 
=={{header|Ruby}}==
Extending [[Basic_bitmap_storage#Ruby]]
<syntaxhighlight lang="ruby">class Pixmap
# 'open' is a class method
def self.open(filename)
Line 2,306 ⟶ 2,270:
# then, convert to grayscale
Pixmap.open('testcross.ppm').to_grayscale!.save('testgray.ppm')</syntaxhighlight>
 
=={{header|Rust}}==
<syntaxhighlight lang="rust">
parser.rs:
use super::{Color, ImageFormat};
Line 2,592 ⟶ 2,555:
}
</syntaxhighlight>
 
 
=={{header|Scala}}==
Uses the [[Basic_bitmap_storage#Scala|Basic Bitmap Storage]] and [[Grayscale_image#Scala|Grayscale Bitmap]] classes.
Line 2,599 ⟶ 2,560:
See also Task [[Write_ppm_file#Scala|Write a PPM File]] for save code.
 
<syntaxhighlight lang="scala">import scala.io._
import scala.swing._
import java.io._
Line 2,647 ⟶ 2,608:
 
Usage:
<syntaxhighlight lang="scala">object PixmapTest {
def main(args: Array[String]): Unit = {
val img=Pixmap.load("image.ppm").get
Line 2,662 ⟶ 2,623:
}
}</syntaxhighlight>
 
=={{header|Seed7}}==
<syntaxhighlight lang="seed7">$ include "seed7_05.s7i";
include "draw.s7i";
include "color.s7i";
Line 2,700 ⟶ 2,660:
end if;
end func;</syntaxhighlight>
 
=={{header|Tcl}}==
{{libheader|Tk}}
The actual PPM reader is built into the photo image engine:
<syntaxhighlight lang="tcl">package require Tk
 
proc readPPM {image file} {
Line 2,710 ⟶ 2,669:
}</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:
<syntaxhighlight lang="tcl">package require Tk
 
proc grayscaleFile {filename {newFilename ""}} {
Line 2,733 ⟶ 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:
<syntaxhighlight lang="tcl">package require Tk
 
proc grayscaleFile {filename {newFilename ""}} {
Line 2,745 ⟶ 2,704:
}
}</syntaxhighlight>
 
=={{header|UNIX Shell}}==
{{works with|ksh93}}
Line 2,751 ⟶ 2,709:
 
Add the following functions to the <tt>RGBColor_t</tt> type
<syntaxhighlight lang="bash"> function setrgb {
_.r=$1
_.g=$2
Line 2,764 ⟶ 2,722:
 
Add the following function to the <tt>Bitmap_t</tt> type
<syntaxhighlight lang="bash"> function grayscale {
RGBColor_t c
for ((y=0; y<_.height; y++)); do
Line 2,805 ⟶ 2,763:
 
Now we can:
<syntaxhighlight lang="bash">Bitmap_t c
c.read "$HOME/tmp/bitmap.ppm"
c.to_s
Line 2,818 ⟶ 2,776:
c.to_s
c.write "$HOME/tmp/bitmap_g.ppm"</syntaxhighlight>
 
=={{header|Vedit macro language}}==
<syntaxhighlight lang="vedit">// Load a PPM file
// @10 = filename
// On return:
Line 2,839 ⟶ 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]].
<syntaxhighlight lang="vedit">// Load RGB image
Reg_Set(10, "|(USER_MACRO)\example.ppm")
Call("LOAD_PPM")
Line 2,858 ⟶ 2,815:
Buf_Switch(#20) Buf_Quit(OK)
return</syntaxhighlight>
 
=={{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.
<syntaxhighlight lang="ecmascript">import "graphics" for Canvas, ImageData, Color
import "dome" for Window, Process
import "io" for FileSystem
Line 2,937 ⟶ 2,893:
 
var Game = Bitmap.new("Lenna100.ppm", "Lenna100_gs.jpg", 1048, 512)</syntaxhighlight>
 
=={{header|XPL0}}==
The simplicity of redirecting an input file on the command line doesn't
Line 2,943 ⟶ 2,898:
files larger than 1280x1024 are clipped to the screen dimensions.
 
<syntaxhighlight lang=XPL0"xpl0">include c:\cxpl\codes; \intrinsic 'code' declarations
 
func OpenInFile; \Open for input the file typed on command line
Line 2,988 ⟶ 2,943:
SetVid(3); \restore normal text display
]</syntaxhighlight>
 
=={{header|Yabasic}}==
<syntaxhighlight lang=Yabasic"yabasic">sub readPPM(f$)
local ff, x, y, t$, dcol$, wid, hei
 
Line 3,017 ⟶ 2,971:
return true
end sub</syntaxhighlight>
 
=={{header|zkl}}==
{{trans|FBSL}}
Line 3,024 ⟶ 2,977:
I used a slightly different image from what is shown, but the results are the same.
[[File:FBSLLena.png|right]]
<syntaxhighlight 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,035 ⟶ 2,988:
 
File("lenaGrey.ppm","wb").write(image);</syntaxhighlight>
 
 
 
{{omit from|AWK}}
{{omit from|Lotus 123 Macro Scripting}}
10,327

edits