Bitmap/Read a PPM file: Difference between revisions

no edit summary
(→‎{{header|Raku}}: Fix up some internal links)
No edit summary
Line 373:
=={{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#}}
<lang Delphi>
program BtmAndPpm;
 
{$APPTYPE CONSOLE}
 
{$R *.res}
 
uses
System.SysUtils,
System.Classes,
Vcl.Graphics;
 
type
TBitmapHelper = class helper for TBitmap
private
public
procedure SaveAsPPM(FileName: TFileName);
procedure LoadFromPPM(FileName: TFileName);
end;
 
{ TBitmapHelper }
 
procedure TBitmapHelper.SaveAsPPM(FileName: TFileName);
var
i, j, color: Integer;
Header: AnsiString;
ppm: TMemoryStream;
begin
ppm := TMemoryStream.Create;
try
Header := Format('P6'#10'%d %d'#10'255'#10, [Self.Width, Self.Height]);
writeln(Header);
ppm.Write(Tbytes(Header), Length(Header));
 
for i := 0 to Self.Height - 1 do
for j := 0 to Self.Width - 1 do
begin
color := ColorToRGB(Self.Canvas.Pixels[i, j]);
ppm.Write(color, 3);
end;
ppm.SaveToFile(FileName);
finally
ppm.Free;
end;
end;
 
function BigEndianFix(Color: TColor): TColor;
begin
Result := Color;
end;
 
procedure TBitmapHelper.LoadFromPPM(FileName: TFileName);
var
p: Integer;
ppm: TMemoryStream;
// buffer: Byte;
sW, sH: string;
temp: AnsiChar;
W, H: Integer;
Color: TColor;
 
function ReadChar: AnsiChar;
begin
ppm.Read(Result, 1);
end;
 
begin
ppm := TMemoryStream.Create;
ppm.LoadFromFile(FileName);
if ReadChar + ReadChar <> 'P6' then
exit;
 
repeat
temp := ReadChar;
if temp in ['0'..'9'] then
sW := sW + temp;
until temp = ' ';
 
repeat
temp := ReadChar;
if temp in ['0'..'9'] then
sH := sH + temp;
until temp = #10;
 
W := StrToInt(sW);
H := StrToInt(sH);
 
if ReadChar + ReadChar + ReadChar <> '255' then
exit;
 
ReadChar(); //skip newLine
 
SetSize(W, H);
p := 0;
while ppm.Read(Color, 3) > 0 do
begin
Canvas.Pixels[p mod W, p div W] := Color;
inc(p);
end;
ppm.Free;
end;
 
begin
with TBitmap.Create do
begin
// Load bmp
LoadFromFile('Input.bmp');
 
// Save as ppm
SaveAsPPM('Output.ppm');
 
// Load as ppm
LoadFromPPM('Output.ppm');
 
// Save as bmp
SaveToFile('Output.bmp');
 
Free;
end;
end.
</lang>
 
=={{header|E}}==
478

edits