How to resolve the algorithm Bitmap/Write a PPM file step by step in the Raku programming language

Published on 12 May 2024 09:40 PM

How to resolve the algorithm Bitmap/Write a PPM file step by step in the Raku programming language

Table of Contents

Problem Statement

Using the data storage type defined on this page for raster images, write the image to a PPM file (binary P6 preferred). (Read the definition of PPM file on Wikipedia.)

Let's start with the solution:

Step by Step solution about How to resolve the algorithm Bitmap/Write a PPM file step by step in the Raku programming language

Source code in the raku programming language

class Pixel { has uint8 ($.R, $.G, $.B) }
class Bitmap {
    has UInt ($.width, $.height);
    has Pixel @!data;

    method fill(Pixel $p) {
        @!data = $p.clone xx ($!width*$!height)
    }
    method pixel(
	  $i where ^$!width,
	  $j where ^$!height
	  --> Pixel
      ) is rw { @!data[$i*$!height + $j] }

    method data { @!data }
}

role PPM {
    method P6 returns Blob {
	"P6\n{self.width} {self.height}\n255\n".encode('ascii')
	~ Blob.new: flat map { .R, .G, .B }, self.data
    }
}

my Bitmap $b = Bitmap.new(width => 125, height => 125) but PPM;
for flat ^$b.height X ^$b.width -> $i, $j {
    $b.pixel($i, $j) = Pixel.new: :R($i*2), :G($j*2), :B(255-$i*2);
}

$*OUT.write: $b.P6;


  

You may also check:How to resolve the algorithm Jewels and stones step by step in the 11l programming language
You may also check:How to resolve the algorithm Topic variable step by step in the Wren programming language
You may also check:How to resolve the algorithm JSON step by step in the Emacs Lisp programming language
You may also check:How to resolve the algorithm Comments step by step in the Slate programming language
You may also check:How to resolve the algorithm Compare a list of strings step by step in the XProfan programming language