Bitmap/Read a PPM file: Difference between revisions
Content added Content deleted
(Added solution for Action!) |
Thundergnat (talk | contribs) m (syntax highlighting fixup automation) |
||
Line 10:
{{trans|Python}}
<
Byte r, g, b
Line 107:
print(‘Grey PPM:’)
bitmap.togreyscale()
print(bitmap.writeppmp3())</
{{out}}
Line 126:
{{libheader|Action! Bitmap tools}}
{{libheader|Action! Tool Kit}}
<
PROC DecodeSize(CHAR ARRAY s BYTE POINTER width,height)
Line 261:
PrintF("Loading %S...%E%E",path2)
Load(path2)
RETURN</
{{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}}==
<
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;</
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.
<
F1, F2 : File_Type;
begin
Line 362:
Close (F1);
Close (F2);
end;</
=={{header|AutoHotkey}}==
Line 368:
Only ppm6 files supported.
<
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</
=={{header|BBC BASIC}}==
{{works with|BBC BASIC for Windows}}
<
IF f%=0 ERROR 100, "Failed to open input file"
Line 457:
GCOL 1
LINE x%*2,y%*2,x%*2,y%*2
ENDPROC</
=={{header|C}}==
Line 465:
Interface:
<syntaxhighlight lang
Implementation:
<
#define PPMREADBUFLEN 256
Line 506:
return img;
}
}</
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):
<
#include "imglib.h"
Line 525:
free_img(source); free_img((image)idest);
return 0;
}</
=={{header|C sharp|C#}}==
Tested with [[Write ppm file#C.23|this solution.]]
<
class PPMReader
{
Line 562:
return bitmap;
}
}</
=={{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.
<
(in-package #:rgb-pixel-buffer)
Line 640:
(export 'read-ppm-image)
</syntaxhighlight>
To read the feep.ppm file as shown on the description page for the ppm format use:
<
(read-ppm-image "feep.ppm")
</syntaxhighlight>
=={{header|D}}==
Line 652:
Class helper for read and write Bitmap's and Ppm's
{{Trans|C#}}
<
program BtmAndPpm;
Line 780:
end;
end.
</syntaxhighlight>
=={{header|E}}==
<
def readPPM(inputStream) {
Line 838:
image.replace(data.snapshot())
return image
}</
[[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.
<
makeGrayscale \
.fromColor(readPPM(<import:java.io.makeFileInputStream>(inputFile))) \
.toColor() \
.writePPM(<import:java.io.makeFileOutputStream>(outputFile))
}</
=={{header|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>
Usage in accordance with Grayscale Task:
<
Colorful = ppm:read("colorful.ppm"),
Gray = ros_bitmap:convert(ros_bitmap:convert(Colorful, grey), rgb),
ppm:write(Gray, "gray.ppm"),
</syntaxhighlight>
=={{header|Euphoria}}==
<
function get2(integer fn)
Line 1,004:
close(fn)
return image
end function</
Converting an image to grayscale:
<
image = read_ppm("image.ppm")
image = to_gray(image)
image = to_color(image)
write_ppm("image_gray.ppm",image)</
=={{header|FBSL}}==
Line 1,018:
'''24-bpp P6 PPM solution:'''
[[File:FBSLLena.png|right]]
<
DIM colored = ".\\Lena.ppm", grayscale = ".\\LenaGry.ppm"
Line 1,035:
NEXT
FILEPUT(FILEOPEN(grayscale, BINARY_NEW), FILEGET): FILECLOSE(FILEOPEN) ' Save buffer</
=={{header|Forth}}==
<
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</
=={{header|Fortran}}==
Line 1,082:
(This function is part of module RCImageIO, see [[Write ppm file#Fortran|Write ppm file]])
<
integer, intent(in) :: u
type(rgbimage), intent(out) :: img
Line 1,123:
end if
end subroutine read_ppm</
'''Notes''':
Line 1,131:
=={{header|Go}}==
<
import (
Line 1,198:
}
return b, f.Close()
}</
Demonstration program, also demonstrating functions from task [[Grayscale image]]:
<
// Files required to build supporting package raster are found in:
Line 1,227:
fmt.Println(err)
}
}</
=={{header|Haskell}}==
The definition of <tt>Bitmap.Netpbm.readNetpbm</tt> is given [[Write ppm file|here]].
<
import Bitmap.RGB
import Bitmap.Gray
Line 1,242:
(readNetpbm "original.ppm" :: IO (Image RealWorld RGB)) >>=
stToIO . toGrayImage >>=
writeNetpbm "new.pgm"</
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:
<
(readNetpbm "original.ppm" :: IO (Image RealWorld RGB)) >>=
stToIO . (toRGBImage <=< toGrayImage) >>=
writeNetpbm "new.ppm"</
=={{header|J}}==
'''Solution:'''<br>
Uses <tt>makeRGB</tt> from [[Basic bitmap storage#J|Basic bitmap storage]].
<
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
)</
'''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.
<
myimgGray=: toColor toGray myimg
myimgGray writeppm jpath '~temp/myimgGray.ppm'</
=={{header|Julia}}==
{{works with|Julia|0.6}}
<
rgbimg = load("data/bitmapInputTest.ppm")
greyimg = Gray.(rgbimg)
save("data/bitmapOutputTest.ppm", greyimg)</
=={{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.
<
import java.awt.Color
Line 1,410:
}
}
}</
=={{header|Lua}}==
<
local fp = io.open( filename, "rb" )
if fp == nil then return nil end
Line 1,446:
return image
end</
=={{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.
<
Module Checkit {
Function Bitmap {
Line 1,622:
Checkit
</syntaxhighlight>
=={{header|Mathematica}}/ {{header|Wolfram Language}}==
<
</syntaxhighlight>
=={{header|Nim}}==
<
import bitmap
import streams
Line 1,719:
when isMainModule:
let image = readPPM("output.ppm")
echo image.h, " ", image.w</
=={{header|OCaml}}==
<
let ic = open_in filename in
let line = input_line ic in
Line 1,760:
r_channel,
g_channel,
b_channel)</
and converting a given color file to grayscale:
<
let img = read_ppm ~filename:"logo.ppm" in
let img = to_color(to_grayscale ~img) in
output_ppm ~oc:stdout ~img;
;;</
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>:
<
import
Bitmap
Line 1,856:
%% Omitted: Write
end</
The actual task:
<
[BitmapIO Grayscale] = {Module.link ['BitmapIO.ozf' 'Grayscale.ozf']}
Line 1,865:
G = {Grayscale.toGraymap B}
in
{BitmapIO.write {Grayscale.fromGraymap G} "greyimage.ppm"}</
=={{header|Perl}}==
Line 1,871:
{{libheader|Imlib2}}
<
use strict;
Line 1,884:
$img->save("out1.png");
exit 0;</
=={{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
<
function read_ppm(string filename)
Line 1,920:
sequence img = read_ppm("Lena.ppm")
img = to_grey(img)
write_ppm("LenaGray.ppm",img)</
=={{header|PicoLisp}}==
<
(in File
(unless (and `(hex "5036") (rd 2)) # P6
Line 1,940:
(map
'((X) (set X (list (rd 1) (rd 1) (rd 1))))
Y ) ) ) ) ) )</
Read a color image "img.ppm", convert and write to "img.pgm":
<
=={{header|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;</
=={{header|PureBasic}}==
<
r.c
g.c
Line 2,069:
EndIf
EndIf
EndProcedure</
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]]
<
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</
=={{header|Python}}==
Line 2,085:
Extending the example given [[Basic_bitmap_storage#Alternative_version|here]]
<
# String masquerading as ppm file (version P3)
Line 2,153:
4 4 4 0 0 0 0 0 0 0 0 0
'''</
=={{header|Racket}}==
<
#lang racket
(require racket/draw)
Line 2,179:
(send dc draw-point x y)))
bm))
</syntaxhighlight>
=={{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
class Bitmap {
has UInt ($.width, $.height);
Line 2,221:
grayscale($b);
'./camelia-gs.pgm'.IO.open(:bin, :w).write: $b.P5;</
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.
<
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. */</
{{out|output}}
<pre>
Line 2,273:
=={{header|Ruby}}==
Extending [[Basic_bitmap_storage#Ruby]]
<
# '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')</
=={{header|Rust}}==
<
parser.rs:
use super::{Color, ImageFormat};
Line 2,591:
println!("Dimensions: {} x {}", image.height, image.width);
}
</syntaxhighlight>
Line 2,599:
See also Task [[Write_ppm_file#Scala|Write a PPM File]] for save code.
<
import scala.swing._
import java.io._
Line 2,644:
out
}
}</
Usage:
<
def main(args: Array[String]): Unit = {
val img=Pixmap.load("image.ppm").get
Line 2,661:
}
}
}</
=={{header|Seed7}}==
<
include "draw.s7i";
include "color.s7i";
Line 2,699:
close(ppmFile);
end if;
end func;</
=={{header|Tcl}}==
{{libheader|Tk}}
The actual PPM reader is built into the photo image engine:
<
proc readPPM {image file} {
$image read $file -format ppm
}</
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:
<
proc grayscaleFile {filename {newFilename ""}} {
Line 2,730:
image delete $buffer
}
}</
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:
<
proc grayscaleFile {filename {newFilename ""}} {
Line 2,744:
image delete $buffer
}
}</
=={{header|UNIX Shell}}==
Line 2,751:
Add the following functions to the <tt>RGBColor_t</tt> type
<
_.r=$1
_.g=$2
Line 2,761:
_.g=$x
_.b=$x
}</
Add the following function to the <tt>Bitmap_t</tt> type
<
RGBColor_t c
for ((y=0; y<_.height; y++)); do
Line 2,802:
fi
exec 4<&-
}</
Now we can:
<
c.read "$HOME/tmp/bitmap.ppm"
c.to_s
Line 2,817:
c.grayscale
c.to_s
c.write "$HOME/tmp/bitmap_g.ppm"</
=={{header|Vedit macro language}}==
<
// @10 = filename
// On return:
Line 2,836:
Search("|X", ADVANCE) // skip maxval (assume 255)
Del_Block(0,CP) // remove the header
Return</
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]].
<
Reg_Set(10, "|(USER_MACRO)\example.ppm")
Call("LOAD_PPM")
Line 2,857:
// Cleanup and exit
Buf_Switch(#20) Buf_Quit(OK)
return</
=={{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.
<
import "dome" for Window, Process
import "io" for FileSystem
Line 2,936:
}
var Game = Bitmap.new("Lenna100.ppm", "Lenna100_gs.jpg", 1048, 512)</
=={{header|XPL0}}==
Line 2,943:
files larger than 1280x1024 are clipped to the screen dimensions.
<
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
]</
=={{header|Yabasic}}==
<
local ff, x, y, t$, dcol$, wid, hei
Line 3,016:
return true
end sub</
=={{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]]
<
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);</
|