Instruction
stringlengths
45
106
input_code
stringlengths
1
13.7k
output_code
stringlengths
1
13.7k
Please provide an equivalent version of this Delphi code in Python.
program btm2ppm; uses System.SysUtils, System.Classes, Vcl.Graphics; type TBitmapHelper = class helper for TBitmap public procedure SaveAsPPM(FileName: TFileName); end; 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; begin with TBitmap.Create do begin LoadFromFile('Input.bmp'); SaveAsPPM('Output.ppm'); Free; end; end.
import io ppmfileout = io.StringIO('') def writeppmp3(self, f): self.writeppm(f, ppmformat='P3') def writeppm(self, f, ppmformat='P6'): assert ppmformat in ['P3', 'P6'], 'Format wrong' magic = ppmformat + '\n' comment = ' maxval = max(max(max(bit) for bit in row) for row in self.map) assert ppmformat == 'P3' or 0 <= maxval < 256, 'R,G,B must fit in a byte' if ppmformat == 'P6': fwrite = lambda s: f.write(bytes(s, 'UTF-8')) maxval = 255 else: fwrite = f.write numsize=len(str(maxval)) fwrite(magic) fwrite(comment) fwrite('%i %i\n%i\n' % (self.width, self.height, maxval)) for h in range(self.height-1, -1, -1): for w in range(self.width): r, g, b = self.get(w, h) if ppmformat == 'P3': fwrite(' %*i %*i %*i' % (numsize, r, numsize, g, numsize, b)) else: fwrite('%c%c%c' % (r, g, b)) if ppmformat == 'P3': fwrite('\n') Bitmap.writeppmp3 = writeppmp3 Bitmap.writeppm = writeppm bitmap = Bitmap(4, 4, black) bitmap.fillrect(1, 0, 1, 2, white) bitmap.set(3, 3, Colour(127, 0, 63)) bitmap.writeppmp3(ppmfileout) print(ppmfileout.getvalue()) ppmfileout = open('tmp.ppm', 'wb') bitmap.writeppm(ppmfileout) ppmfileout.close()
Transform the following Delphi implementation into VB, maintaining the same output and logic.
program btm2ppm; uses System.SysUtils, System.Classes, Vcl.Graphics; type TBitmapHelper = class helper for TBitmap public procedure SaveAsPPM(FileName: TFileName); end; 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; begin with TBitmap.Create do begin LoadFromFile('Input.bmp'); SaveAsPPM('Output.ppm'); Free; end; end.
Public Shared Sub SaveRasterBitmapToPpmFile(ByVal rasterBitmap As RasterBitmap, ByVal filepath As String) Dim header As String = String.Format("P6{0}{1}{2}{3}{0}255{0}", vbLf, rasterBitmap.Width, " "c, rasterBitmap.Height) Dim bufferSize As Integer = header.Length + (rasterBitmap.Width * rasterBitmap.Height * 3) Dim bytes(bufferSize - 1) As Byte Buffer.BlockCopy(Encoding.ASCII.GetBytes(header.ToString), 0, bytes, 0, header.Length) Dim index As Integer = header.Length For y As Integer = 0 To rasterBitmap.Height - 1 For x As Integer = 0 To rasterBitmap.Width - 1 Dim color As Rgb = rasterBitmap.GetPixel(x, y) bytes(index) = color.R bytes(index + 1) = color.G bytes(index + 2) = color.B index += 3 Next Next My.Computer.FileSystem.WriteAllBytes(filepath, bytes, False) End Sub
Rewrite this program in Go while keeping its functionality equivalent to the Delphi version.
program btm2ppm; uses System.SysUtils, System.Classes, Vcl.Graphics; type TBitmapHelper = class helper for TBitmap public procedure SaveAsPPM(FileName: TFileName); end; 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; begin with TBitmap.Create do begin LoadFromFile('Input.bmp'); SaveAsPPM('Output.ppm'); Free; end; end.
package raster import ( "fmt" "io" "os" ) func (b *Bitmap) WritePpmTo(w io.Writer) (err error) { if _, err = fmt.Fprintln(w, "P6"); err != nil { return } for _, c := range b.Comments { if _, err = fmt.Fprintln(w, c); err != nil { return } } _, err = fmt.Fprintf(w, "%d %d\n255\n", b.cols, b.rows) if err != nil { return } b3 := make([]byte, 3*len(b.px)) n1 := 0 for _, px := range b.px { b3[n1] = px.R b3[n1+1] = px.G b3[n1+2] = px.B n1 += 3 } if _, err = w.Write(b3); err != nil { return } return } func (b *Bitmap) WritePpmFile(fn string) (err error) { var f *os.File if f, err = os.Create(fn); err != nil { return } if err = b.WritePpmTo(f); err != nil { return } return f.Close() }
Rewrite this program in C while keeping its functionality equivalent to the Erlang version.
-module(ppm). -export([ppm/1, write/2]). -define(WHITESPACE, <<10>>). -define(SPACE, <<32>>). -record(bitmap, { pixels = nil, shape = {0, 0} }). ppm(Bitmap) -> {Width, Height} = Bitmap#bitmap.shape, Pixels = ppm_pixels(Bitmap), Maxval = 255, list_to_binary([ header(), width_and_height(Width, Height), maxval(Maxval), Pixels]). write(Bitmap, Filename) -> Ppm = ppm(Bitmap), {ok, File} = file:open(Filename, [binary, write]), file:write(File, Ppm), file:close(File). header() -> [<<"P6">>, ?WHITESPACE]. width_and_height(Width, Height) -> [encode_decimal(Width), ?SPACE, encode_decimal(Height), ?WHITESPACE]. maxval(Maxval) -> [encode_decimal(Maxval), ?WHITESPACE]. ppm_pixels(Bitmap) -> array:to_list(Bitmap#bitmap.pixels). encode_decimal(Number) -> integer_to_list(Number).
#include <stdlib.h> #include <stdio.h> int main(void) { const int dimx = 800, dimy = 800; int i, j; FILE *fp = fopen("first.ppm", "wb"); (void) fprintf(fp, "P6\n%d %d\n255\n", dimx, dimy); for (j = 0; j < dimy; ++j) { for (i = 0; i < dimx; ++i) { static unsigned char color[3]; color[0] = i % 256; color[1] = j % 256; color[2] = (i * j) % 256; (void) fwrite(color, 1, 3, fp); } } (void) fclose(fp); return EXIT_SUCCESS; }
Please provide an equivalent version of this Erlang code in C#.
-module(ppm). -export([ppm/1, write/2]). -define(WHITESPACE, <<10>>). -define(SPACE, <<32>>). -record(bitmap, { pixels = nil, shape = {0, 0} }). ppm(Bitmap) -> {Width, Height} = Bitmap#bitmap.shape, Pixels = ppm_pixels(Bitmap), Maxval = 255, list_to_binary([ header(), width_and_height(Width, Height), maxval(Maxval), Pixels]). write(Bitmap, Filename) -> Ppm = ppm(Bitmap), {ok, File} = file:open(Filename, [binary, write]), file:write(File, Ppm), file:close(File). header() -> [<<"P6">>, ?WHITESPACE]. width_and_height(Width, Height) -> [encode_decimal(Width), ?SPACE, encode_decimal(Height), ?WHITESPACE]. maxval(Maxval) -> [encode_decimal(Maxval), ?WHITESPACE]. ppm_pixels(Bitmap) -> array:to_list(Bitmap#bitmap.pixels). encode_decimal(Number) -> integer_to_list(Number).
using System; using System.IO; class PPMWriter { public static void WriteBitmapToPPM(string file, Bitmap bitmap) { var writer = new StreamWriter(file); writer.WriteLine("P6"); writer.WriteLine($"{bitmap.Width} {bitmap.Height}"); writer.WriteLine("255"); writer.Close(); var writerB = new BinaryWriter(new FileStream(file, FileMode.Append)); for (int x = 0; x < bitmap.Height; x++) for (int y = 0; y < bitmap.Width; y++) { Color color = bitmap.GetPixel(y, x); writerB.Write(color.R); writerB.Write(color.G); writerB.Write(color.B); } writerB.Close(); } }
Change the following Erlang code into C++ without altering its purpose.
-module(ppm). -export([ppm/1, write/2]). -define(WHITESPACE, <<10>>). -define(SPACE, <<32>>). -record(bitmap, { pixels = nil, shape = {0, 0} }). ppm(Bitmap) -> {Width, Height} = Bitmap#bitmap.shape, Pixels = ppm_pixels(Bitmap), Maxval = 255, list_to_binary([ header(), width_and_height(Width, Height), maxval(Maxval), Pixels]). write(Bitmap, Filename) -> Ppm = ppm(Bitmap), {ok, File} = file:open(Filename, [binary, write]), file:write(File, Ppm), file:close(File). header() -> [<<"P6">>, ?WHITESPACE]. width_and_height(Width, Height) -> [encode_decimal(Width), ?SPACE, encode_decimal(Height), ?WHITESPACE]. maxval(Maxval) -> [encode_decimal(Maxval), ?WHITESPACE]. ppm_pixels(Bitmap) -> array:to_list(Bitmap#bitmap.pixels). encode_decimal(Number) -> integer_to_list(Number).
#include <fstream> int main() { constexpr auto dimx = 800u, dimy = 800u; std::ofstream ofs("first.ppm", ios_base::out | ios_base::binary); ofs << "P6\n" << dimx << ' ' << dimy << "\n255\n"; for (auto j = 0u; j < dimy; ++j) for (auto i = 0u; i < dimx; ++i) ofs << static_cast<char>(i % 256) << static_cast<char>(j % 256) << static_cast<char>((i * j) % 256); }
Change the following Erlang code into Python without altering its purpose.
-module(ppm). -export([ppm/1, write/2]). -define(WHITESPACE, <<10>>). -define(SPACE, <<32>>). -record(bitmap, { pixels = nil, shape = {0, 0} }). ppm(Bitmap) -> {Width, Height} = Bitmap#bitmap.shape, Pixels = ppm_pixels(Bitmap), Maxval = 255, list_to_binary([ header(), width_and_height(Width, Height), maxval(Maxval), Pixels]). write(Bitmap, Filename) -> Ppm = ppm(Bitmap), {ok, File} = file:open(Filename, [binary, write]), file:write(File, Ppm), file:close(File). header() -> [<<"P6">>, ?WHITESPACE]. width_and_height(Width, Height) -> [encode_decimal(Width), ?SPACE, encode_decimal(Height), ?WHITESPACE]. maxval(Maxval) -> [encode_decimal(Maxval), ?WHITESPACE]. ppm_pixels(Bitmap) -> array:to_list(Bitmap#bitmap.pixels). encode_decimal(Number) -> integer_to_list(Number).
import io ppmfileout = io.StringIO('') def writeppmp3(self, f): self.writeppm(f, ppmformat='P3') def writeppm(self, f, ppmformat='P6'): assert ppmformat in ['P3', 'P6'], 'Format wrong' magic = ppmformat + '\n' comment = ' maxval = max(max(max(bit) for bit in row) for row in self.map) assert ppmformat == 'P3' or 0 <= maxval < 256, 'R,G,B must fit in a byte' if ppmformat == 'P6': fwrite = lambda s: f.write(bytes(s, 'UTF-8')) maxval = 255 else: fwrite = f.write numsize=len(str(maxval)) fwrite(magic) fwrite(comment) fwrite('%i %i\n%i\n' % (self.width, self.height, maxval)) for h in range(self.height-1, -1, -1): for w in range(self.width): r, g, b = self.get(w, h) if ppmformat == 'P3': fwrite(' %*i %*i %*i' % (numsize, r, numsize, g, numsize, b)) else: fwrite('%c%c%c' % (r, g, b)) if ppmformat == 'P3': fwrite('\n') Bitmap.writeppmp3 = writeppmp3 Bitmap.writeppm = writeppm bitmap = Bitmap(4, 4, black) bitmap.fillrect(1, 0, 1, 2, white) bitmap.set(3, 3, Colour(127, 0, 63)) bitmap.writeppmp3(ppmfileout) print(ppmfileout.getvalue()) ppmfileout = open('tmp.ppm', 'wb') bitmap.writeppm(ppmfileout) ppmfileout.close()
Preserve the algorithm and functionality while converting the code from Erlang to VB.
-module(ppm). -export([ppm/1, write/2]). -define(WHITESPACE, <<10>>). -define(SPACE, <<32>>). -record(bitmap, { pixels = nil, shape = {0, 0} }). ppm(Bitmap) -> {Width, Height} = Bitmap#bitmap.shape, Pixels = ppm_pixels(Bitmap), Maxval = 255, list_to_binary([ header(), width_and_height(Width, Height), maxval(Maxval), Pixels]). write(Bitmap, Filename) -> Ppm = ppm(Bitmap), {ok, File} = file:open(Filename, [binary, write]), file:write(File, Ppm), file:close(File). header() -> [<<"P6">>, ?WHITESPACE]. width_and_height(Width, Height) -> [encode_decimal(Width), ?SPACE, encode_decimal(Height), ?WHITESPACE]. maxval(Maxval) -> [encode_decimal(Maxval), ?WHITESPACE]. ppm_pixels(Bitmap) -> array:to_list(Bitmap#bitmap.pixels). encode_decimal(Number) -> integer_to_list(Number).
Public Shared Sub SaveRasterBitmapToPpmFile(ByVal rasterBitmap As RasterBitmap, ByVal filepath As String) Dim header As String = String.Format("P6{0}{1}{2}{3}{0}255{0}", vbLf, rasterBitmap.Width, " "c, rasterBitmap.Height) Dim bufferSize As Integer = header.Length + (rasterBitmap.Width * rasterBitmap.Height * 3) Dim bytes(bufferSize - 1) As Byte Buffer.BlockCopy(Encoding.ASCII.GetBytes(header.ToString), 0, bytes, 0, header.Length) Dim index As Integer = header.Length For y As Integer = 0 To rasterBitmap.Height - 1 For x As Integer = 0 To rasterBitmap.Width - 1 Dim color As Rgb = rasterBitmap.GetPixel(x, y) bytes(index) = color.R bytes(index + 1) = color.G bytes(index + 2) = color.B index += 3 Next Next My.Computer.FileSystem.WriteAllBytes(filepath, bytes, False) End Sub
Ensure the translated Go code behaves exactly like the original Erlang snippet.
-module(ppm). -export([ppm/1, write/2]). -define(WHITESPACE, <<10>>). -define(SPACE, <<32>>). -record(bitmap, { pixels = nil, shape = {0, 0} }). ppm(Bitmap) -> {Width, Height} = Bitmap#bitmap.shape, Pixels = ppm_pixels(Bitmap), Maxval = 255, list_to_binary([ header(), width_and_height(Width, Height), maxval(Maxval), Pixels]). write(Bitmap, Filename) -> Ppm = ppm(Bitmap), {ok, File} = file:open(Filename, [binary, write]), file:write(File, Ppm), file:close(File). header() -> [<<"P6">>, ?WHITESPACE]. width_and_height(Width, Height) -> [encode_decimal(Width), ?SPACE, encode_decimal(Height), ?WHITESPACE]. maxval(Maxval) -> [encode_decimal(Maxval), ?WHITESPACE]. ppm_pixels(Bitmap) -> array:to_list(Bitmap#bitmap.pixels). encode_decimal(Number) -> integer_to_list(Number).
package raster import ( "fmt" "io" "os" ) func (b *Bitmap) WritePpmTo(w io.Writer) (err error) { if _, err = fmt.Fprintln(w, "P6"); err != nil { return } for _, c := range b.Comments { if _, err = fmt.Fprintln(w, c); err != nil { return } } _, err = fmt.Fprintf(w, "%d %d\n255\n", b.cols, b.rows) if err != nil { return } b3 := make([]byte, 3*len(b.px)) n1 := 0 for _, px := range b.px { b3[n1] = px.R b3[n1+1] = px.G b3[n1+2] = px.B n1 += 3 } if _, err = w.Write(b3); err != nil { return } return } func (b *Bitmap) WritePpmFile(fn string) (err error) { var f *os.File if f, err = os.Create(fn); err != nil { return } if err = b.WritePpmTo(f); err != nil { return } return f.Close() }
Convert the following code from Forth to C, ensuring the logic remains intact.
: write-ppm { bmp fid -- } s" P6" fid write-line throw bmp bdim swap 0 <# bl hold #s #> fid write-file throw 0 <# #s #> fid write-line throw s" 255" fid write-line throw bmp bdata bmp bdim * pixels bounds do i 3 fid write-file throw pixel +loop ; s" red.ppm" w/o create-file throw test over write-ppm close-file throw
#include <stdlib.h> #include <stdio.h> int main(void) { const int dimx = 800, dimy = 800; int i, j; FILE *fp = fopen("first.ppm", "wb"); (void) fprintf(fp, "P6\n%d %d\n255\n", dimx, dimy); for (j = 0; j < dimy; ++j) { for (i = 0; i < dimx; ++i) { static unsigned char color[3]; color[0] = i % 256; color[1] = j % 256; color[2] = (i * j) % 256; (void) fwrite(color, 1, 3, fp); } } (void) fclose(fp); return EXIT_SUCCESS; }
Generate a C# translation of this Forth snippet without changing its computational steps.
: write-ppm { bmp fid -- } s" P6" fid write-line throw bmp bdim swap 0 <# bl hold #s #> fid write-file throw 0 <# #s #> fid write-line throw s" 255" fid write-line throw bmp bdata bmp bdim * pixels bounds do i 3 fid write-file throw pixel +loop ; s" red.ppm" w/o create-file throw test over write-ppm close-file throw
using System; using System.IO; class PPMWriter { public static void WriteBitmapToPPM(string file, Bitmap bitmap) { var writer = new StreamWriter(file); writer.WriteLine("P6"); writer.WriteLine($"{bitmap.Width} {bitmap.Height}"); writer.WriteLine("255"); writer.Close(); var writerB = new BinaryWriter(new FileStream(file, FileMode.Append)); for (int x = 0; x < bitmap.Height; x++) for (int y = 0; y < bitmap.Width; y++) { Color color = bitmap.GetPixel(y, x); writerB.Write(color.R); writerB.Write(color.G); writerB.Write(color.B); } writerB.Close(); } }
Write the same code in C++ as shown below in Forth.
: write-ppm { bmp fid -- } s" P6" fid write-line throw bmp bdim swap 0 <# bl hold #s #> fid write-file throw 0 <# #s #> fid write-line throw s" 255" fid write-line throw bmp bdata bmp bdim * pixels bounds do i 3 fid write-file throw pixel +loop ; s" red.ppm" w/o create-file throw test over write-ppm close-file throw
#include <fstream> int main() { constexpr auto dimx = 800u, dimy = 800u; std::ofstream ofs("first.ppm", ios_base::out | ios_base::binary); ofs << "P6\n" << dimx << ' ' << dimy << "\n255\n"; for (auto j = 0u; j < dimy; ++j) for (auto i = 0u; i < dimx; ++i) ofs << static_cast<char>(i % 256) << static_cast<char>(j % 256) << static_cast<char>((i * j) % 256); }
Convert this Forth snippet to Java and keep its semantics consistent.
: write-ppm { bmp fid -- } s" P6" fid write-line throw bmp bdim swap 0 <# bl hold #s #> fid write-file throw 0 <# #s #> fid write-line throw s" 255" fid write-line throw bmp bdata bmp bdim * pixels bounds do i 3 fid write-file throw pixel +loop ; s" red.ppm" w/o create-file throw test over write-ppm close-file throw
import java.io.BufferedOutputStream; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.nio.charset.StandardCharsets; public class PPMWriter { public void bitmapToPPM(File file, BasicBitmapStorage bitmap) throws IOException { file.delete(); try (var os = new FileOutputStream(file, true); var bw = new BufferedOutputStream(os)) { var header = String.format("P6\n%d %d\n255\n", bitmap.getWidth(), bitmap.getHeight()); bw.write(header.getBytes(StandardCharsets.US_ASCII)); for (var y = 0; y < bitmap.getHeight(); y++) { for (var x = 0; x < bitmap.getWidth(); x++) { var pixel = bitmap.getPixel(x, y); bw.write(pixel.getRed()); bw.write(pixel.getGreen()); bw.write(pixel.getBlue()); } } } } }
Generate an equivalent Python version of this Forth code.
: write-ppm { bmp fid -- } s" P6" fid write-line throw bmp bdim swap 0 <# bl hold #s #> fid write-file throw 0 <# #s #> fid write-line throw s" 255" fid write-line throw bmp bdata bmp bdim * pixels bounds do i 3 fid write-file throw pixel +loop ; s" red.ppm" w/o create-file throw test over write-ppm close-file throw
import io ppmfileout = io.StringIO('') def writeppmp3(self, f): self.writeppm(f, ppmformat='P3') def writeppm(self, f, ppmformat='P6'): assert ppmformat in ['P3', 'P6'], 'Format wrong' magic = ppmformat + '\n' comment = ' maxval = max(max(max(bit) for bit in row) for row in self.map) assert ppmformat == 'P3' or 0 <= maxval < 256, 'R,G,B must fit in a byte' if ppmformat == 'P6': fwrite = lambda s: f.write(bytes(s, 'UTF-8')) maxval = 255 else: fwrite = f.write numsize=len(str(maxval)) fwrite(magic) fwrite(comment) fwrite('%i %i\n%i\n' % (self.width, self.height, maxval)) for h in range(self.height-1, -1, -1): for w in range(self.width): r, g, b = self.get(w, h) if ppmformat == 'P3': fwrite(' %*i %*i %*i' % (numsize, r, numsize, g, numsize, b)) else: fwrite('%c%c%c' % (r, g, b)) if ppmformat == 'P3': fwrite('\n') Bitmap.writeppmp3 = writeppmp3 Bitmap.writeppm = writeppm bitmap = Bitmap(4, 4, black) bitmap.fillrect(1, 0, 1, 2, white) bitmap.set(3, 3, Colour(127, 0, 63)) bitmap.writeppmp3(ppmfileout) print(ppmfileout.getvalue()) ppmfileout = open('tmp.ppm', 'wb') bitmap.writeppm(ppmfileout) ppmfileout.close()
Keep all operations the same but rewrite the snippet in VB.
: write-ppm { bmp fid -- } s" P6" fid write-line throw bmp bdim swap 0 <# bl hold #s #> fid write-file throw 0 <# #s #> fid write-line throw s" 255" fid write-line throw bmp bdata bmp bdim * pixels bounds do i 3 fid write-file throw pixel +loop ; s" red.ppm" w/o create-file throw test over write-ppm close-file throw
Public Shared Sub SaveRasterBitmapToPpmFile(ByVal rasterBitmap As RasterBitmap, ByVal filepath As String) Dim header As String = String.Format("P6{0}{1}{2}{3}{0}255{0}", vbLf, rasterBitmap.Width, " "c, rasterBitmap.Height) Dim bufferSize As Integer = header.Length + (rasterBitmap.Width * rasterBitmap.Height * 3) Dim bytes(bufferSize - 1) As Byte Buffer.BlockCopy(Encoding.ASCII.GetBytes(header.ToString), 0, bytes, 0, header.Length) Dim index As Integer = header.Length For y As Integer = 0 To rasterBitmap.Height - 1 For x As Integer = 0 To rasterBitmap.Width - 1 Dim color As Rgb = rasterBitmap.GetPixel(x, y) bytes(index) = color.R bytes(index + 1) = color.G bytes(index + 2) = color.B index += 3 Next Next My.Computer.FileSystem.WriteAllBytes(filepath, bytes, False) End Sub
Can you help me rewrite this code in Go instead of Forth, keeping it the same logically?
: write-ppm { bmp fid -- } s" P6" fid write-line throw bmp bdim swap 0 <# bl hold #s #> fid write-file throw 0 <# #s #> fid write-line throw s" 255" fid write-line throw bmp bdata bmp bdim * pixels bounds do i 3 fid write-file throw pixel +loop ; s" red.ppm" w/o create-file throw test over write-ppm close-file throw
package raster import ( "fmt" "io" "os" ) func (b *Bitmap) WritePpmTo(w io.Writer) (err error) { if _, err = fmt.Fprintln(w, "P6"); err != nil { return } for _, c := range b.Comments { if _, err = fmt.Fprintln(w, c); err != nil { return } } _, err = fmt.Fprintf(w, "%d %d\n255\n", b.cols, b.rows) if err != nil { return } b3 := make([]byte, 3*len(b.px)) n1 := 0 for _, px := range b.px { b3[n1] = px.R b3[n1+1] = px.G b3[n1+2] = px.B n1 += 3 } if _, err = w.Write(b3); err != nil { return } return } func (b *Bitmap) WritePpmFile(fn string) (err error) { var f *os.File if f, err = os.Create(fn); err != nil { return } if err = b.WritePpmTo(f); err != nil { return } return f.Close() }
Port the provided Fortran code into C# while preserving the original functionality.
program main use rgbimage_m implicit none integer :: nx, ny, i, j, k type(rgbimage) :: im nx = 400 ny = 300 call im%init(nx, ny) do i = 1, nx do j = 1, ny call im%set_pixel(i, j, [(nint(rand()*255), k=1,3)]) end do end do call im%write('fig.ppm') end program
using System; using System.IO; class PPMWriter { public static void WriteBitmapToPPM(string file, Bitmap bitmap) { var writer = new StreamWriter(file); writer.WriteLine("P6"); writer.WriteLine($"{bitmap.Width} {bitmap.Height}"); writer.WriteLine("255"); writer.Close(); var writerB = new BinaryWriter(new FileStream(file, FileMode.Append)); for (int x = 0; x < bitmap.Height; x++) for (int y = 0; y < bitmap.Width; y++) { Color color = bitmap.GetPixel(y, x); writerB.Write(color.R); writerB.Write(color.G); writerB.Write(color.B); } writerB.Close(); } }
Produce a language-to-language conversion: from Fortran to C++, same semantics.
program main use rgbimage_m implicit none integer :: nx, ny, i, j, k type(rgbimage) :: im nx = 400 ny = 300 call im%init(nx, ny) do i = 1, nx do j = 1, ny call im%set_pixel(i, j, [(nint(rand()*255), k=1,3)]) end do end do call im%write('fig.ppm') end program
#include <fstream> int main() { constexpr auto dimx = 800u, dimy = 800u; std::ofstream ofs("first.ppm", ios_base::out | ios_base::binary); ofs << "P6\n" << dimx << ' ' << dimy << "\n255\n"; for (auto j = 0u; j < dimy; ++j) for (auto i = 0u; i < dimx; ++i) ofs << static_cast<char>(i % 256) << static_cast<char>(j % 256) << static_cast<char>((i * j) % 256); }
Produce a functionally identical C code for the snippet given in Fortran.
program main use rgbimage_m implicit none integer :: nx, ny, i, j, k type(rgbimage) :: im nx = 400 ny = 300 call im%init(nx, ny) do i = 1, nx do j = 1, ny call im%set_pixel(i, j, [(nint(rand()*255), k=1,3)]) end do end do call im%write('fig.ppm') end program
#include <stdlib.h> #include <stdio.h> int main(void) { const int dimx = 800, dimy = 800; int i, j; FILE *fp = fopen("first.ppm", "wb"); (void) fprintf(fp, "P6\n%d %d\n255\n", dimx, dimy); for (j = 0; j < dimy; ++j) { for (i = 0; i < dimx; ++i) { static unsigned char color[3]; color[0] = i % 256; color[1] = j % 256; color[2] = (i * j) % 256; (void) fwrite(color, 1, 3, fp); } } (void) fclose(fp); return EXIT_SUCCESS; }
Change the programming language of this snippet from Fortran to Go without modifying what it does.
program main use rgbimage_m implicit none integer :: nx, ny, i, j, k type(rgbimage) :: im nx = 400 ny = 300 call im%init(nx, ny) do i = 1, nx do j = 1, ny call im%set_pixel(i, j, [(nint(rand()*255), k=1,3)]) end do end do call im%write('fig.ppm') end program
package raster import ( "fmt" "io" "os" ) func (b *Bitmap) WritePpmTo(w io.Writer) (err error) { if _, err = fmt.Fprintln(w, "P6"); err != nil { return } for _, c := range b.Comments { if _, err = fmt.Fprintln(w, c); err != nil { return } } _, err = fmt.Fprintf(w, "%d %d\n255\n", b.cols, b.rows) if err != nil { return } b3 := make([]byte, 3*len(b.px)) n1 := 0 for _, px := range b.px { b3[n1] = px.R b3[n1+1] = px.G b3[n1+2] = px.B n1 += 3 } if _, err = w.Write(b3); err != nil { return } return } func (b *Bitmap) WritePpmFile(fn string) (err error) { var f *os.File if f, err = os.Create(fn); err != nil { return } if err = b.WritePpmTo(f); err != nil { return } return f.Close() }
Translate the given Fortran code snippet into Java without altering its behavior.
program main use rgbimage_m implicit none integer :: nx, ny, i, j, k type(rgbimage) :: im nx = 400 ny = 300 call im%init(nx, ny) do i = 1, nx do j = 1, ny call im%set_pixel(i, j, [(nint(rand()*255), k=1,3)]) end do end do call im%write('fig.ppm') end program
import java.io.BufferedOutputStream; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.nio.charset.StandardCharsets; public class PPMWriter { public void bitmapToPPM(File file, BasicBitmapStorage bitmap) throws IOException { file.delete(); try (var os = new FileOutputStream(file, true); var bw = new BufferedOutputStream(os)) { var header = String.format("P6\n%d %d\n255\n", bitmap.getWidth(), bitmap.getHeight()); bw.write(header.getBytes(StandardCharsets.US_ASCII)); for (var y = 0; y < bitmap.getHeight(); y++) { for (var x = 0; x < bitmap.getWidth(); x++) { var pixel = bitmap.getPixel(x, y); bw.write(pixel.getRed()); bw.write(pixel.getGreen()); bw.write(pixel.getBlue()); } } } } }
Transform the following Fortran implementation into Python, maintaining the same output and logic.
program main use rgbimage_m implicit none integer :: nx, ny, i, j, k type(rgbimage) :: im nx = 400 ny = 300 call im%init(nx, ny) do i = 1, nx do j = 1, ny call im%set_pixel(i, j, [(nint(rand()*255), k=1,3)]) end do end do call im%write('fig.ppm') end program
import io ppmfileout = io.StringIO('') def writeppmp3(self, f): self.writeppm(f, ppmformat='P3') def writeppm(self, f, ppmformat='P6'): assert ppmformat in ['P3', 'P6'], 'Format wrong' magic = ppmformat + '\n' comment = ' maxval = max(max(max(bit) for bit in row) for row in self.map) assert ppmformat == 'P3' or 0 <= maxval < 256, 'R,G,B must fit in a byte' if ppmformat == 'P6': fwrite = lambda s: f.write(bytes(s, 'UTF-8')) maxval = 255 else: fwrite = f.write numsize=len(str(maxval)) fwrite(magic) fwrite(comment) fwrite('%i %i\n%i\n' % (self.width, self.height, maxval)) for h in range(self.height-1, -1, -1): for w in range(self.width): r, g, b = self.get(w, h) if ppmformat == 'P3': fwrite(' %*i %*i %*i' % (numsize, r, numsize, g, numsize, b)) else: fwrite('%c%c%c' % (r, g, b)) if ppmformat == 'P3': fwrite('\n') Bitmap.writeppmp3 = writeppmp3 Bitmap.writeppm = writeppm bitmap = Bitmap(4, 4, black) bitmap.fillrect(1, 0, 1, 2, white) bitmap.set(3, 3, Colour(127, 0, 63)) bitmap.writeppmp3(ppmfileout) print(ppmfileout.getvalue()) ppmfileout = open('tmp.ppm', 'wb') bitmap.writeppm(ppmfileout) ppmfileout.close()
Write a version of this Fortran function in PHP with identical behavior.
program main use rgbimage_m implicit none integer :: nx, ny, i, j, k type(rgbimage) :: im nx = 400 ny = 300 call im%init(nx, ny) do i = 1, nx do j = 1, ny call im%set_pixel(i, j, [(nint(rand()*255), k=1,3)]) end do end do call im%write('fig.ppm') end program
class Bitmap { public $data; public $w; public $h; public function __construct($w = 16, $h = 16){ $white = array_fill(0, $w, array(255,255,255)); $this->data = array_fill(0, $h, $white); $this->w = $w; $this->h = $h; } public function fill($x = 0, $y = 0, $w = null, $h = null, $color = array(0,0,0)){ if (is_null($w)) $w = $this->w; if (is_null($h)) $h = $this->h; $w += $x; $h += $y; for ($i = $y; $i < $h; $i++){ for ($j = $x; $j < $w; $j++){ $this->setPixel($j, $i, $color); } } } public function setPixel($x, $y, $color = array(0,0,0)){ if ($x >= $this->w) return false; if ($x < 0) return false; if ($y >= $this->h) return false; if ($y < 0) return false; $this->data[$y][$x] = $color; } public function getPixel($x, $y){ return $this->data[$y][$x]; } public function writeP6($filename){ $fh = fopen($filename, 'w'); if (!$fh) return false; fputs($fh, "P6 {$this->w} {$this->h} 255\n"); foreach ($this->data as $row){ foreach($row as $pixel){ fputs($fh, pack('C', $pixel[0])); fputs($fh, pack('C', $pixel[1])); fputs($fh, pack('C', $pixel[2])); } } fclose($fh); } } $b = new Bitmap(16,16); $b->fill(); $b->fill(2, 2, 18, 18, array(240,240,240)); $b->setPixel(0, 15, array(255,0,0)); $b->writeP6('p6.ppm');
Translate the given Haskell code snippet into C without altering its behavior.
module Bitmap.Netpbm(readNetpbm, writeNetpbm) where import Bitmap import Data.Char import System.IO import Control.Monad import Control.Monad.ST import Data.Array.ST nil :: a nil = undefined readNetpbm :: forall c. Color c => FilePath -> IO (Image RealWorld c) readNetpbm path = do let die = fail "readNetpbm: bad format" ppm <- readFile path let (s, rest) = splitAt 2 ppm unless (s == magicNumber) die let getNum :: String -> IO (Int, String) getNum ppm = do let (s, rest) = span isDigit $ skipBlanks ppm when (null s) die return (read s, rest) (width, rest) <- getNum rest (height, rest) <- getNum rest (_, c : rest) <- if getMaxval then getNum rest else return (nil, rest) unless (isSpace c) die i <- stToIO $ listImage width height $ fromNetpbm $ map fromEnum rest return i where skipBlanks = dropWhile isSpace . until ((/= '#') . head) (tail . dropWhile (/= '\n')) . dropWhile isSpace magicNumber = netpbmMagicNumber (nil :: c) getMaxval = not $ null $ netpbmMaxval (nil :: c) writeNetpbm :: forall c. Color c => FilePath -> Image RealWorld c -> IO () writeNetpbm path i = withFile path WriteMode $ \h -> do (width, height) <- stToIO $ dimensions i let w = hPutStrLn h w $ magicNumber w $ show width ++ " " ++ show height unless (null maxval) (w maxval) stToIO (getPixels i) >>= hPutStr h . toNetpbm where magicNumber = netpbmMagicNumber (nil :: c) maxval = netpbmMaxval (nil :: c)
#include <stdlib.h> #include <stdio.h> int main(void) { const int dimx = 800, dimy = 800; int i, j; FILE *fp = fopen("first.ppm", "wb"); (void) fprintf(fp, "P6\n%d %d\n255\n", dimx, dimy); for (j = 0; j < dimy; ++j) { for (i = 0; i < dimx; ++i) { static unsigned char color[3]; color[0] = i % 256; color[1] = j % 256; color[2] = (i * j) % 256; (void) fwrite(color, 1, 3, fp); } } (void) fclose(fp); return EXIT_SUCCESS; }
Convert this Haskell snippet to C# and keep its semantics consistent.
module Bitmap.Netpbm(readNetpbm, writeNetpbm) where import Bitmap import Data.Char import System.IO import Control.Monad import Control.Monad.ST import Data.Array.ST nil :: a nil = undefined readNetpbm :: forall c. Color c => FilePath -> IO (Image RealWorld c) readNetpbm path = do let die = fail "readNetpbm: bad format" ppm <- readFile path let (s, rest) = splitAt 2 ppm unless (s == magicNumber) die let getNum :: String -> IO (Int, String) getNum ppm = do let (s, rest) = span isDigit $ skipBlanks ppm when (null s) die return (read s, rest) (width, rest) <- getNum rest (height, rest) <- getNum rest (_, c : rest) <- if getMaxval then getNum rest else return (nil, rest) unless (isSpace c) die i <- stToIO $ listImage width height $ fromNetpbm $ map fromEnum rest return i where skipBlanks = dropWhile isSpace . until ((/= '#') . head) (tail . dropWhile (/= '\n')) . dropWhile isSpace magicNumber = netpbmMagicNumber (nil :: c) getMaxval = not $ null $ netpbmMaxval (nil :: c) writeNetpbm :: forall c. Color c => FilePath -> Image RealWorld c -> IO () writeNetpbm path i = withFile path WriteMode $ \h -> do (width, height) <- stToIO $ dimensions i let w = hPutStrLn h w $ magicNumber w $ show width ++ " " ++ show height unless (null maxval) (w maxval) stToIO (getPixels i) >>= hPutStr h . toNetpbm where magicNumber = netpbmMagicNumber (nil :: c) maxval = netpbmMaxval (nil :: c)
using System; using System.IO; class PPMWriter { public static void WriteBitmapToPPM(string file, Bitmap bitmap) { var writer = new StreamWriter(file); writer.WriteLine("P6"); writer.WriteLine($"{bitmap.Width} {bitmap.Height}"); writer.WriteLine("255"); writer.Close(); var writerB = new BinaryWriter(new FileStream(file, FileMode.Append)); for (int x = 0; x < bitmap.Height; x++) for (int y = 0; y < bitmap.Width; y++) { Color color = bitmap.GetPixel(y, x); writerB.Write(color.R); writerB.Write(color.G); writerB.Write(color.B); } writerB.Close(); } }
Generate an equivalent C++ version of this Haskell code.
module Bitmap.Netpbm(readNetpbm, writeNetpbm) where import Bitmap import Data.Char import System.IO import Control.Monad import Control.Monad.ST import Data.Array.ST nil :: a nil = undefined readNetpbm :: forall c. Color c => FilePath -> IO (Image RealWorld c) readNetpbm path = do let die = fail "readNetpbm: bad format" ppm <- readFile path let (s, rest) = splitAt 2 ppm unless (s == magicNumber) die let getNum :: String -> IO (Int, String) getNum ppm = do let (s, rest) = span isDigit $ skipBlanks ppm when (null s) die return (read s, rest) (width, rest) <- getNum rest (height, rest) <- getNum rest (_, c : rest) <- if getMaxval then getNum rest else return (nil, rest) unless (isSpace c) die i <- stToIO $ listImage width height $ fromNetpbm $ map fromEnum rest return i where skipBlanks = dropWhile isSpace . until ((/= '#') . head) (tail . dropWhile (/= '\n')) . dropWhile isSpace magicNumber = netpbmMagicNumber (nil :: c) getMaxval = not $ null $ netpbmMaxval (nil :: c) writeNetpbm :: forall c. Color c => FilePath -> Image RealWorld c -> IO () writeNetpbm path i = withFile path WriteMode $ \h -> do (width, height) <- stToIO $ dimensions i let w = hPutStrLn h w $ magicNumber w $ show width ++ " " ++ show height unless (null maxval) (w maxval) stToIO (getPixels i) >>= hPutStr h . toNetpbm where magicNumber = netpbmMagicNumber (nil :: c) maxval = netpbmMaxval (nil :: c)
#include <fstream> int main() { constexpr auto dimx = 800u, dimy = 800u; std::ofstream ofs("first.ppm", ios_base::out | ios_base::binary); ofs << "P6\n" << dimx << ' ' << dimy << "\n255\n"; for (auto j = 0u; j < dimy; ++j) for (auto i = 0u; i < dimx; ++i) ofs << static_cast<char>(i % 256) << static_cast<char>(j % 256) << static_cast<char>((i * j) % 256); }
Ensure the translated Java code behaves exactly like the original Haskell snippet.
module Bitmap.Netpbm(readNetpbm, writeNetpbm) where import Bitmap import Data.Char import System.IO import Control.Monad import Control.Monad.ST import Data.Array.ST nil :: a nil = undefined readNetpbm :: forall c. Color c => FilePath -> IO (Image RealWorld c) readNetpbm path = do let die = fail "readNetpbm: bad format" ppm <- readFile path let (s, rest) = splitAt 2 ppm unless (s == magicNumber) die let getNum :: String -> IO (Int, String) getNum ppm = do let (s, rest) = span isDigit $ skipBlanks ppm when (null s) die return (read s, rest) (width, rest) <- getNum rest (height, rest) <- getNum rest (_, c : rest) <- if getMaxval then getNum rest else return (nil, rest) unless (isSpace c) die i <- stToIO $ listImage width height $ fromNetpbm $ map fromEnum rest return i where skipBlanks = dropWhile isSpace . until ((/= '#') . head) (tail . dropWhile (/= '\n')) . dropWhile isSpace magicNumber = netpbmMagicNumber (nil :: c) getMaxval = not $ null $ netpbmMaxval (nil :: c) writeNetpbm :: forall c. Color c => FilePath -> Image RealWorld c -> IO () writeNetpbm path i = withFile path WriteMode $ \h -> do (width, height) <- stToIO $ dimensions i let w = hPutStrLn h w $ magicNumber w $ show width ++ " " ++ show height unless (null maxval) (w maxval) stToIO (getPixels i) >>= hPutStr h . toNetpbm where magicNumber = netpbmMagicNumber (nil :: c) maxval = netpbmMaxval (nil :: c)
import java.io.BufferedOutputStream; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.nio.charset.StandardCharsets; public class PPMWriter { public void bitmapToPPM(File file, BasicBitmapStorage bitmap) throws IOException { file.delete(); try (var os = new FileOutputStream(file, true); var bw = new BufferedOutputStream(os)) { var header = String.format("P6\n%d %d\n255\n", bitmap.getWidth(), bitmap.getHeight()); bw.write(header.getBytes(StandardCharsets.US_ASCII)); for (var y = 0; y < bitmap.getHeight(); y++) { for (var x = 0; x < bitmap.getWidth(); x++) { var pixel = bitmap.getPixel(x, y); bw.write(pixel.getRed()); bw.write(pixel.getGreen()); bw.write(pixel.getBlue()); } } } } }
Write the same code in Python as shown below in Haskell.
module Bitmap.Netpbm(readNetpbm, writeNetpbm) where import Bitmap import Data.Char import System.IO import Control.Monad import Control.Monad.ST import Data.Array.ST nil :: a nil = undefined readNetpbm :: forall c. Color c => FilePath -> IO (Image RealWorld c) readNetpbm path = do let die = fail "readNetpbm: bad format" ppm <- readFile path let (s, rest) = splitAt 2 ppm unless (s == magicNumber) die let getNum :: String -> IO (Int, String) getNum ppm = do let (s, rest) = span isDigit $ skipBlanks ppm when (null s) die return (read s, rest) (width, rest) <- getNum rest (height, rest) <- getNum rest (_, c : rest) <- if getMaxval then getNum rest else return (nil, rest) unless (isSpace c) die i <- stToIO $ listImage width height $ fromNetpbm $ map fromEnum rest return i where skipBlanks = dropWhile isSpace . until ((/= '#') . head) (tail . dropWhile (/= '\n')) . dropWhile isSpace magicNumber = netpbmMagicNumber (nil :: c) getMaxval = not $ null $ netpbmMaxval (nil :: c) writeNetpbm :: forall c. Color c => FilePath -> Image RealWorld c -> IO () writeNetpbm path i = withFile path WriteMode $ \h -> do (width, height) <- stToIO $ dimensions i let w = hPutStrLn h w $ magicNumber w $ show width ++ " " ++ show height unless (null maxval) (w maxval) stToIO (getPixels i) >>= hPutStr h . toNetpbm where magicNumber = netpbmMagicNumber (nil :: c) maxval = netpbmMaxval (nil :: c)
import io ppmfileout = io.StringIO('') def writeppmp3(self, f): self.writeppm(f, ppmformat='P3') def writeppm(self, f, ppmformat='P6'): assert ppmformat in ['P3', 'P6'], 'Format wrong' magic = ppmformat + '\n' comment = ' maxval = max(max(max(bit) for bit in row) for row in self.map) assert ppmformat == 'P3' or 0 <= maxval < 256, 'R,G,B must fit in a byte' if ppmformat == 'P6': fwrite = lambda s: f.write(bytes(s, 'UTF-8')) maxval = 255 else: fwrite = f.write numsize=len(str(maxval)) fwrite(magic) fwrite(comment) fwrite('%i %i\n%i\n' % (self.width, self.height, maxval)) for h in range(self.height-1, -1, -1): for w in range(self.width): r, g, b = self.get(w, h) if ppmformat == 'P3': fwrite(' %*i %*i %*i' % (numsize, r, numsize, g, numsize, b)) else: fwrite('%c%c%c' % (r, g, b)) if ppmformat == 'P3': fwrite('\n') Bitmap.writeppmp3 = writeppmp3 Bitmap.writeppm = writeppm bitmap = Bitmap(4, 4, black) bitmap.fillrect(1, 0, 1, 2, white) bitmap.set(3, 3, Colour(127, 0, 63)) bitmap.writeppmp3(ppmfileout) print(ppmfileout.getvalue()) ppmfileout = open('tmp.ppm', 'wb') bitmap.writeppm(ppmfileout) ppmfileout.close()
Generate an equivalent VB version of this Haskell code.
module Bitmap.Netpbm(readNetpbm, writeNetpbm) where import Bitmap import Data.Char import System.IO import Control.Monad import Control.Monad.ST import Data.Array.ST nil :: a nil = undefined readNetpbm :: forall c. Color c => FilePath -> IO (Image RealWorld c) readNetpbm path = do let die = fail "readNetpbm: bad format" ppm <- readFile path let (s, rest) = splitAt 2 ppm unless (s == magicNumber) die let getNum :: String -> IO (Int, String) getNum ppm = do let (s, rest) = span isDigit $ skipBlanks ppm when (null s) die return (read s, rest) (width, rest) <- getNum rest (height, rest) <- getNum rest (_, c : rest) <- if getMaxval then getNum rest else return (nil, rest) unless (isSpace c) die i <- stToIO $ listImage width height $ fromNetpbm $ map fromEnum rest return i where skipBlanks = dropWhile isSpace . until ((/= '#') . head) (tail . dropWhile (/= '\n')) . dropWhile isSpace magicNumber = netpbmMagicNumber (nil :: c) getMaxval = not $ null $ netpbmMaxval (nil :: c) writeNetpbm :: forall c. Color c => FilePath -> Image RealWorld c -> IO () writeNetpbm path i = withFile path WriteMode $ \h -> do (width, height) <- stToIO $ dimensions i let w = hPutStrLn h w $ magicNumber w $ show width ++ " " ++ show height unless (null maxval) (w maxval) stToIO (getPixels i) >>= hPutStr h . toNetpbm where magicNumber = netpbmMagicNumber (nil :: c) maxval = netpbmMaxval (nil :: c)
Public Shared Sub SaveRasterBitmapToPpmFile(ByVal rasterBitmap As RasterBitmap, ByVal filepath As String) Dim header As String = String.Format("P6{0}{1}{2}{3}{0}255{0}", vbLf, rasterBitmap.Width, " "c, rasterBitmap.Height) Dim bufferSize As Integer = header.Length + (rasterBitmap.Width * rasterBitmap.Height * 3) Dim bytes(bufferSize - 1) As Byte Buffer.BlockCopy(Encoding.ASCII.GetBytes(header.ToString), 0, bytes, 0, header.Length) Dim index As Integer = header.Length For y As Integer = 0 To rasterBitmap.Height - 1 For x As Integer = 0 To rasterBitmap.Width - 1 Dim color As Rgb = rasterBitmap.GetPixel(x, y) bytes(index) = color.R bytes(index + 1) = color.G bytes(index + 2) = color.B index += 3 Next Next My.Computer.FileSystem.WriteAllBytes(filepath, bytes, False) End Sub
Maintain the same structure and functionality when rewriting this code in Go.
module Bitmap.Netpbm(readNetpbm, writeNetpbm) where import Bitmap import Data.Char import System.IO import Control.Monad import Control.Monad.ST import Data.Array.ST nil :: a nil = undefined readNetpbm :: forall c. Color c => FilePath -> IO (Image RealWorld c) readNetpbm path = do let die = fail "readNetpbm: bad format" ppm <- readFile path let (s, rest) = splitAt 2 ppm unless (s == magicNumber) die let getNum :: String -> IO (Int, String) getNum ppm = do let (s, rest) = span isDigit $ skipBlanks ppm when (null s) die return (read s, rest) (width, rest) <- getNum rest (height, rest) <- getNum rest (_, c : rest) <- if getMaxval then getNum rest else return (nil, rest) unless (isSpace c) die i <- stToIO $ listImage width height $ fromNetpbm $ map fromEnum rest return i where skipBlanks = dropWhile isSpace . until ((/= '#') . head) (tail . dropWhile (/= '\n')) . dropWhile isSpace magicNumber = netpbmMagicNumber (nil :: c) getMaxval = not $ null $ netpbmMaxval (nil :: c) writeNetpbm :: forall c. Color c => FilePath -> Image RealWorld c -> IO () writeNetpbm path i = withFile path WriteMode $ \h -> do (width, height) <- stToIO $ dimensions i let w = hPutStrLn h w $ magicNumber w $ show width ++ " " ++ show height unless (null maxval) (w maxval) stToIO (getPixels i) >>= hPutStr h . toNetpbm where magicNumber = netpbmMagicNumber (nil :: c) maxval = netpbmMaxval (nil :: c)
package raster import ( "fmt" "io" "os" ) func (b *Bitmap) WritePpmTo(w io.Writer) (err error) { if _, err = fmt.Fprintln(w, "P6"); err != nil { return } for _, c := range b.Comments { if _, err = fmt.Fprintln(w, c); err != nil { return } } _, err = fmt.Fprintf(w, "%d %d\n255\n", b.cols, b.rows) if err != nil { return } b3 := make([]byte, 3*len(b.px)) n1 := 0 for _, px := range b.px { b3[n1] = px.R b3[n1+1] = px.G b3[n1+2] = px.B n1 += 3 } if _, err = w.Write(b3); err != nil { return } return } func (b *Bitmap) WritePpmFile(fn string) (err error) { var f *os.File if f, err = os.Create(fn); err != nil { return } if err = b.WritePpmTo(f); err != nil { return } return f.Close() }
Port the provided J code into C while preserving the original functionality.
require 'files' writeppm=:dyad define header=. 'P6',LF,(":1 0{$x),LF,'255',LF (header,,x{a.) fwrite y )
#include <stdlib.h> #include <stdio.h> int main(void) { const int dimx = 800, dimy = 800; int i, j; FILE *fp = fopen("first.ppm", "wb"); (void) fprintf(fp, "P6\n%d %d\n255\n", dimx, dimy); for (j = 0; j < dimy; ++j) { for (i = 0; i < dimx; ++i) { static unsigned char color[3]; color[0] = i % 256; color[1] = j % 256; color[2] = (i * j) % 256; (void) fwrite(color, 1, 3, fp); } } (void) fclose(fp); return EXIT_SUCCESS; }
Preserve the algorithm and functionality while converting the code from J to C#.
require 'files' writeppm=:dyad define header=. 'P6',LF,(":1 0{$x),LF,'255',LF (header,,x{a.) fwrite y )
using System; using System.IO; class PPMWriter { public static void WriteBitmapToPPM(string file, Bitmap bitmap) { var writer = new StreamWriter(file); writer.WriteLine("P6"); writer.WriteLine($"{bitmap.Width} {bitmap.Height}"); writer.WriteLine("255"); writer.Close(); var writerB = new BinaryWriter(new FileStream(file, FileMode.Append)); for (int x = 0; x < bitmap.Height; x++) for (int y = 0; y < bitmap.Width; y++) { Color color = bitmap.GetPixel(y, x); writerB.Write(color.R); writerB.Write(color.G); writerB.Write(color.B); } writerB.Close(); } }
Convert this J block to C++, preserving its control flow and logic.
require 'files' writeppm=:dyad define header=. 'P6',LF,(":1 0{$x),LF,'255',LF (header,,x{a.) fwrite y )
#include <fstream> int main() { constexpr auto dimx = 800u, dimy = 800u; std::ofstream ofs("first.ppm", ios_base::out | ios_base::binary); ofs << "P6\n" << dimx << ' ' << dimy << "\n255\n"; for (auto j = 0u; j < dimy; ++j) for (auto i = 0u; i < dimx; ++i) ofs << static_cast<char>(i % 256) << static_cast<char>(j % 256) << static_cast<char>((i * j) % 256); }
Write the same code in Java as shown below in J.
require 'files' writeppm=:dyad define header=. 'P6',LF,(":1 0{$x),LF,'255',LF (header,,x{a.) fwrite y )
import java.io.BufferedOutputStream; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.nio.charset.StandardCharsets; public class PPMWriter { public void bitmapToPPM(File file, BasicBitmapStorage bitmap) throws IOException { file.delete(); try (var os = new FileOutputStream(file, true); var bw = new BufferedOutputStream(os)) { var header = String.format("P6\n%d %d\n255\n", bitmap.getWidth(), bitmap.getHeight()); bw.write(header.getBytes(StandardCharsets.US_ASCII)); for (var y = 0; y < bitmap.getHeight(); y++) { for (var x = 0; x < bitmap.getWidth(); x++) { var pixel = bitmap.getPixel(x, y); bw.write(pixel.getRed()); bw.write(pixel.getGreen()); bw.write(pixel.getBlue()); } } } } }
Transform the following J implementation into Python, maintaining the same output and logic.
require 'files' writeppm=:dyad define header=. 'P6',LF,(":1 0{$x),LF,'255',LF (header,,x{a.) fwrite y )
import io ppmfileout = io.StringIO('') def writeppmp3(self, f): self.writeppm(f, ppmformat='P3') def writeppm(self, f, ppmformat='P6'): assert ppmformat in ['P3', 'P6'], 'Format wrong' magic = ppmformat + '\n' comment = ' maxval = max(max(max(bit) for bit in row) for row in self.map) assert ppmformat == 'P3' or 0 <= maxval < 256, 'R,G,B must fit in a byte' if ppmformat == 'P6': fwrite = lambda s: f.write(bytes(s, 'UTF-8')) maxval = 255 else: fwrite = f.write numsize=len(str(maxval)) fwrite(magic) fwrite(comment) fwrite('%i %i\n%i\n' % (self.width, self.height, maxval)) for h in range(self.height-1, -1, -1): for w in range(self.width): r, g, b = self.get(w, h) if ppmformat == 'P3': fwrite(' %*i %*i %*i' % (numsize, r, numsize, g, numsize, b)) else: fwrite('%c%c%c' % (r, g, b)) if ppmformat == 'P3': fwrite('\n') Bitmap.writeppmp3 = writeppmp3 Bitmap.writeppm = writeppm bitmap = Bitmap(4, 4, black) bitmap.fillrect(1, 0, 1, 2, white) bitmap.set(3, 3, Colour(127, 0, 63)) bitmap.writeppmp3(ppmfileout) print(ppmfileout.getvalue()) ppmfileout = open('tmp.ppm', 'wb') bitmap.writeppm(ppmfileout) ppmfileout.close()
Preserve the algorithm and functionality while converting the code from J to VB.
require 'files' writeppm=:dyad define header=. 'P6',LF,(":1 0{$x),LF,'255',LF (header,,x{a.) fwrite y )
Public Shared Sub SaveRasterBitmapToPpmFile(ByVal rasterBitmap As RasterBitmap, ByVal filepath As String) Dim header As String = String.Format("P6{0}{1}{2}{3}{0}255{0}", vbLf, rasterBitmap.Width, " "c, rasterBitmap.Height) Dim bufferSize As Integer = header.Length + (rasterBitmap.Width * rasterBitmap.Height * 3) Dim bytes(bufferSize - 1) As Byte Buffer.BlockCopy(Encoding.ASCII.GetBytes(header.ToString), 0, bytes, 0, header.Length) Dim index As Integer = header.Length For y As Integer = 0 To rasterBitmap.Height - 1 For x As Integer = 0 To rasterBitmap.Width - 1 Dim color As Rgb = rasterBitmap.GetPixel(x, y) bytes(index) = color.R bytes(index + 1) = color.G bytes(index + 2) = color.B index += 3 Next Next My.Computer.FileSystem.WriteAllBytes(filepath, bytes, False) End Sub
Convert this J snippet to Go and keep its semantics consistent.
require 'files' writeppm=:dyad define header=. 'P6',LF,(":1 0{$x),LF,'255',LF (header,,x{a.) fwrite y )
package raster import ( "fmt" "io" "os" ) func (b *Bitmap) WritePpmTo(w io.Writer) (err error) { if _, err = fmt.Fprintln(w, "P6"); err != nil { return } for _, c := range b.Comments { if _, err = fmt.Fprintln(w, c); err != nil { return } } _, err = fmt.Fprintf(w, "%d %d\n255\n", b.cols, b.rows) if err != nil { return } b3 := make([]byte, 3*len(b.px)) n1 := 0 for _, px := range b.px { b3[n1] = px.R b3[n1+1] = px.G b3[n1+2] = px.B n1 += 3 } if _, err = w.Write(b3); err != nil { return } return } func (b *Bitmap) WritePpmFile(fn string) (err error) { var f *os.File if f, err = os.Create(fn); err != nil { return } if err = b.WritePpmTo(f); err != nil { return } return f.Close() }
Produce a functionally identical C code for the snippet given in Julia.
using Images, FileIO h, w = 50, 70 img = zeros(RGB{N0f8}, h, w) img[10:40, 5:35] = colorant"skyblue" for i in 26:50, j in (i-25):40 img[i, j] = colorant"sienna1" end save("data/bitmapWrite.ppm", img) save("data/bitmapWrite.png", img)
#include <stdlib.h> #include <stdio.h> int main(void) { const int dimx = 800, dimy = 800; int i, j; FILE *fp = fopen("first.ppm", "wb"); (void) fprintf(fp, "P6\n%d %d\n255\n", dimx, dimy); for (j = 0; j < dimy; ++j) { for (i = 0; i < dimx; ++i) { static unsigned char color[3]; color[0] = i % 256; color[1] = j % 256; color[2] = (i * j) % 256; (void) fwrite(color, 1, 3, fp); } } (void) fclose(fp); return EXIT_SUCCESS; }
Generate an equivalent C# version of this Julia code.
using Images, FileIO h, w = 50, 70 img = zeros(RGB{N0f8}, h, w) img[10:40, 5:35] = colorant"skyblue" for i in 26:50, j in (i-25):40 img[i, j] = colorant"sienna1" end save("data/bitmapWrite.ppm", img) save("data/bitmapWrite.png", img)
using System; using System.IO; class PPMWriter { public static void WriteBitmapToPPM(string file, Bitmap bitmap) { var writer = new StreamWriter(file); writer.WriteLine("P6"); writer.WriteLine($"{bitmap.Width} {bitmap.Height}"); writer.WriteLine("255"); writer.Close(); var writerB = new BinaryWriter(new FileStream(file, FileMode.Append)); for (int x = 0; x < bitmap.Height; x++) for (int y = 0; y < bitmap.Width; y++) { Color color = bitmap.GetPixel(y, x); writerB.Write(color.R); writerB.Write(color.G); writerB.Write(color.B); } writerB.Close(); } }
Write the same code in C++ as shown below in Julia.
using Images, FileIO h, w = 50, 70 img = zeros(RGB{N0f8}, h, w) img[10:40, 5:35] = colorant"skyblue" for i in 26:50, j in (i-25):40 img[i, j] = colorant"sienna1" end save("data/bitmapWrite.ppm", img) save("data/bitmapWrite.png", img)
#include <fstream> int main() { constexpr auto dimx = 800u, dimy = 800u; std::ofstream ofs("first.ppm", ios_base::out | ios_base::binary); ofs << "P6\n" << dimx << ' ' << dimy << "\n255\n"; for (auto j = 0u; j < dimy; ++j) for (auto i = 0u; i < dimx; ++i) ofs << static_cast<char>(i % 256) << static_cast<char>(j % 256) << static_cast<char>((i * j) % 256); }
Produce a functionally identical Java code for the snippet given in Julia.
using Images, FileIO h, w = 50, 70 img = zeros(RGB{N0f8}, h, w) img[10:40, 5:35] = colorant"skyblue" for i in 26:50, j in (i-25):40 img[i, j] = colorant"sienna1" end save("data/bitmapWrite.ppm", img) save("data/bitmapWrite.png", img)
import java.io.BufferedOutputStream; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.nio.charset.StandardCharsets; public class PPMWriter { public void bitmapToPPM(File file, BasicBitmapStorage bitmap) throws IOException { file.delete(); try (var os = new FileOutputStream(file, true); var bw = new BufferedOutputStream(os)) { var header = String.format("P6\n%d %d\n255\n", bitmap.getWidth(), bitmap.getHeight()); bw.write(header.getBytes(StandardCharsets.US_ASCII)); for (var y = 0; y < bitmap.getHeight(); y++) { for (var x = 0; x < bitmap.getWidth(); x++) { var pixel = bitmap.getPixel(x, y); bw.write(pixel.getRed()); bw.write(pixel.getGreen()); bw.write(pixel.getBlue()); } } } } }
Ensure the translated Python code behaves exactly like the original Julia snippet.
using Images, FileIO h, w = 50, 70 img = zeros(RGB{N0f8}, h, w) img[10:40, 5:35] = colorant"skyblue" for i in 26:50, j in (i-25):40 img[i, j] = colorant"sienna1" end save("data/bitmapWrite.ppm", img) save("data/bitmapWrite.png", img)
import io ppmfileout = io.StringIO('') def writeppmp3(self, f): self.writeppm(f, ppmformat='P3') def writeppm(self, f, ppmformat='P6'): assert ppmformat in ['P3', 'P6'], 'Format wrong' magic = ppmformat + '\n' comment = ' maxval = max(max(max(bit) for bit in row) for row in self.map) assert ppmformat == 'P3' or 0 <= maxval < 256, 'R,G,B must fit in a byte' if ppmformat == 'P6': fwrite = lambda s: f.write(bytes(s, 'UTF-8')) maxval = 255 else: fwrite = f.write numsize=len(str(maxval)) fwrite(magic) fwrite(comment) fwrite('%i %i\n%i\n' % (self.width, self.height, maxval)) for h in range(self.height-1, -1, -1): for w in range(self.width): r, g, b = self.get(w, h) if ppmformat == 'P3': fwrite(' %*i %*i %*i' % (numsize, r, numsize, g, numsize, b)) else: fwrite('%c%c%c' % (r, g, b)) if ppmformat == 'P3': fwrite('\n') Bitmap.writeppmp3 = writeppmp3 Bitmap.writeppm = writeppm bitmap = Bitmap(4, 4, black) bitmap.fillrect(1, 0, 1, 2, white) bitmap.set(3, 3, Colour(127, 0, 63)) bitmap.writeppmp3(ppmfileout) print(ppmfileout.getvalue()) ppmfileout = open('tmp.ppm', 'wb') bitmap.writeppm(ppmfileout) ppmfileout.close()
Keep all operations the same but rewrite the snippet in VB.
using Images, FileIO h, w = 50, 70 img = zeros(RGB{N0f8}, h, w) img[10:40, 5:35] = colorant"skyblue" for i in 26:50, j in (i-25):40 img[i, j] = colorant"sienna1" end save("data/bitmapWrite.ppm", img) save("data/bitmapWrite.png", img)
Public Shared Sub SaveRasterBitmapToPpmFile(ByVal rasterBitmap As RasterBitmap, ByVal filepath As String) Dim header As String = String.Format("P6{0}{1}{2}{3}{0}255{0}", vbLf, rasterBitmap.Width, " "c, rasterBitmap.Height) Dim bufferSize As Integer = header.Length + (rasterBitmap.Width * rasterBitmap.Height * 3) Dim bytes(bufferSize - 1) As Byte Buffer.BlockCopy(Encoding.ASCII.GetBytes(header.ToString), 0, bytes, 0, header.Length) Dim index As Integer = header.Length For y As Integer = 0 To rasterBitmap.Height - 1 For x As Integer = 0 To rasterBitmap.Width - 1 Dim color As Rgb = rasterBitmap.GetPixel(x, y) bytes(index) = color.R bytes(index + 1) = color.G bytes(index + 2) = color.B index += 3 Next Next My.Computer.FileSystem.WriteAllBytes(filepath, bytes, False) End Sub
Transform the following Julia implementation into Go, maintaining the same output and logic.
using Images, FileIO h, w = 50, 70 img = zeros(RGB{N0f8}, h, w) img[10:40, 5:35] = colorant"skyblue" for i in 26:50, j in (i-25):40 img[i, j] = colorant"sienna1" end save("data/bitmapWrite.ppm", img) save("data/bitmapWrite.png", img)
package raster import ( "fmt" "io" "os" ) func (b *Bitmap) WritePpmTo(w io.Writer) (err error) { if _, err = fmt.Fprintln(w, "P6"); err != nil { return } for _, c := range b.Comments { if _, err = fmt.Fprintln(w, c); err != nil { return } } _, err = fmt.Fprintf(w, "%d %d\n255\n", b.cols, b.rows) if err != nil { return } b3 := make([]byte, 3*len(b.px)) n1 := 0 for _, px := range b.px { b3[n1] = px.R b3[n1+1] = px.G b3[n1+2] = px.B n1 += 3 } if _, err = w.Write(b3); err != nil { return } return } func (b *Bitmap) WritePpmFile(fn string) (err error) { var f *os.File if f, err = os.Create(fn); err != nil { return } if err = b.WritePpmTo(f); err != nil { return } return f.Close() }
Transform the following Lua implementation into C, maintaining the same output and logic.
local array_fill = function(vbegin, vend, value) local t = {} for i=vbegin, vend do t[i] = value end return t end Bitmap = {} Bitmap.__index = Bitmap function Bitmap.new(width, height) local self = {} setmetatable(self, Bitmap) local white = array_fill(0, width, {255, 255, 255}) self.data = array_fill(0, height, white) self.width = width self.height = height return self end function Bitmap:writeRawPixel(file, c) local dt dt = string.format("%c", c) file:write(dt) end function Bitmap:writeComment(fh, ...) local strings = {...} local str = "" local result for _, s in pairs(strings) do str = str .. tostring(s) end result = string.format("# %s\n", str) fh:write(result) end function Bitmap:writeP6(filename) local fh = io.open(filename, 'w') if not fh then error(string.format("failed to open %q for writing", filename)) else fh:write(string.format("P6 %d %d 255\n", self.width, self.height)) self:writeComment(fh, "automatically generated at ", os.date()) for _, row in pairs(self.data) do for _, pixel in pairs(row) do self:writeRawPixel(fh, pixel[1]) self:writeRawPixel(fh, pixel[2]) self:writeRawPixel(fh, pixel[3]) end end end end function Bitmap:fill(x, y, width, height, color) width = (width == nil) and self.width or width height = (height == nil) and self.height or height width = width + x height = height + y for i=y, height do for j=x, width do self:setPixel(j, i, color) end end end function Bitmap:setPixel(x, y, color) if x >= self.width then return false elseif x < 0 then return false elseif y >= self.height then return false elseif y < 0 then return false end self.data[y][x] = color return true end function example_colorful_stripes() local w = 260*2 local h = 260*2 local b = Bitmap.new(w, h) b:setPixel(0, 15, {255,68,0}) for i=1, w do for j=1, h do b:setPixel(i, j, { (i + j * 8) % 256, (j + (255 * i)) % 256, (i * j) % 256 } ); end end return b end example_colorful_stripes():writeP6('p6.ppm')
#include <stdlib.h> #include <stdio.h> int main(void) { const int dimx = 800, dimy = 800; int i, j; FILE *fp = fopen("first.ppm", "wb"); (void) fprintf(fp, "P6\n%d %d\n255\n", dimx, dimy); for (j = 0; j < dimy; ++j) { for (i = 0; i < dimx; ++i) { static unsigned char color[3]; color[0] = i % 256; color[1] = j % 256; color[2] = (i * j) % 256; (void) fwrite(color, 1, 3, fp); } } (void) fclose(fp); return EXIT_SUCCESS; }
Change the programming language of this snippet from Lua to C# without modifying what it does.
local array_fill = function(vbegin, vend, value) local t = {} for i=vbegin, vend do t[i] = value end return t end Bitmap = {} Bitmap.__index = Bitmap function Bitmap.new(width, height) local self = {} setmetatable(self, Bitmap) local white = array_fill(0, width, {255, 255, 255}) self.data = array_fill(0, height, white) self.width = width self.height = height return self end function Bitmap:writeRawPixel(file, c) local dt dt = string.format("%c", c) file:write(dt) end function Bitmap:writeComment(fh, ...) local strings = {...} local str = "" local result for _, s in pairs(strings) do str = str .. tostring(s) end result = string.format("# %s\n", str) fh:write(result) end function Bitmap:writeP6(filename) local fh = io.open(filename, 'w') if not fh then error(string.format("failed to open %q for writing", filename)) else fh:write(string.format("P6 %d %d 255\n", self.width, self.height)) self:writeComment(fh, "automatically generated at ", os.date()) for _, row in pairs(self.data) do for _, pixel in pairs(row) do self:writeRawPixel(fh, pixel[1]) self:writeRawPixel(fh, pixel[2]) self:writeRawPixel(fh, pixel[3]) end end end end function Bitmap:fill(x, y, width, height, color) width = (width == nil) and self.width or width height = (height == nil) and self.height or height width = width + x height = height + y for i=y, height do for j=x, width do self:setPixel(j, i, color) end end end function Bitmap:setPixel(x, y, color) if x >= self.width then return false elseif x < 0 then return false elseif y >= self.height then return false elseif y < 0 then return false end self.data[y][x] = color return true end function example_colorful_stripes() local w = 260*2 local h = 260*2 local b = Bitmap.new(w, h) b:setPixel(0, 15, {255,68,0}) for i=1, w do for j=1, h do b:setPixel(i, j, { (i + j * 8) % 256, (j + (255 * i)) % 256, (i * j) % 256 } ); end end return b end example_colorful_stripes():writeP6('p6.ppm')
using System; using System.IO; class PPMWriter { public static void WriteBitmapToPPM(string file, Bitmap bitmap) { var writer = new StreamWriter(file); writer.WriteLine("P6"); writer.WriteLine($"{bitmap.Width} {bitmap.Height}"); writer.WriteLine("255"); writer.Close(); var writerB = new BinaryWriter(new FileStream(file, FileMode.Append)); for (int x = 0; x < bitmap.Height; x++) for (int y = 0; y < bitmap.Width; y++) { Color color = bitmap.GetPixel(y, x); writerB.Write(color.R); writerB.Write(color.G); writerB.Write(color.B); } writerB.Close(); } }
Rewrite the snippet below in C++ so it works the same as the original Lua code.
local array_fill = function(vbegin, vend, value) local t = {} for i=vbegin, vend do t[i] = value end return t end Bitmap = {} Bitmap.__index = Bitmap function Bitmap.new(width, height) local self = {} setmetatable(self, Bitmap) local white = array_fill(0, width, {255, 255, 255}) self.data = array_fill(0, height, white) self.width = width self.height = height return self end function Bitmap:writeRawPixel(file, c) local dt dt = string.format("%c", c) file:write(dt) end function Bitmap:writeComment(fh, ...) local strings = {...} local str = "" local result for _, s in pairs(strings) do str = str .. tostring(s) end result = string.format("# %s\n", str) fh:write(result) end function Bitmap:writeP6(filename) local fh = io.open(filename, 'w') if not fh then error(string.format("failed to open %q for writing", filename)) else fh:write(string.format("P6 %d %d 255\n", self.width, self.height)) self:writeComment(fh, "automatically generated at ", os.date()) for _, row in pairs(self.data) do for _, pixel in pairs(row) do self:writeRawPixel(fh, pixel[1]) self:writeRawPixel(fh, pixel[2]) self:writeRawPixel(fh, pixel[3]) end end end end function Bitmap:fill(x, y, width, height, color) width = (width == nil) and self.width or width height = (height == nil) and self.height or height width = width + x height = height + y for i=y, height do for j=x, width do self:setPixel(j, i, color) end end end function Bitmap:setPixel(x, y, color) if x >= self.width then return false elseif x < 0 then return false elseif y >= self.height then return false elseif y < 0 then return false end self.data[y][x] = color return true end function example_colorful_stripes() local w = 260*2 local h = 260*2 local b = Bitmap.new(w, h) b:setPixel(0, 15, {255,68,0}) for i=1, w do for j=1, h do b:setPixel(i, j, { (i + j * 8) % 256, (j + (255 * i)) % 256, (i * j) % 256 } ); end end return b end example_colorful_stripes():writeP6('p6.ppm')
#include <fstream> int main() { constexpr auto dimx = 800u, dimy = 800u; std::ofstream ofs("first.ppm", ios_base::out | ios_base::binary); ofs << "P6\n" << dimx << ' ' << dimy << "\n255\n"; for (auto j = 0u; j < dimy; ++j) for (auto i = 0u; i < dimx; ++i) ofs << static_cast<char>(i % 256) << static_cast<char>(j % 256) << static_cast<char>((i * j) % 256); }
Rewrite this program in Java while keeping its functionality equivalent to the Lua version.
local array_fill = function(vbegin, vend, value) local t = {} for i=vbegin, vend do t[i] = value end return t end Bitmap = {} Bitmap.__index = Bitmap function Bitmap.new(width, height) local self = {} setmetatable(self, Bitmap) local white = array_fill(0, width, {255, 255, 255}) self.data = array_fill(0, height, white) self.width = width self.height = height return self end function Bitmap:writeRawPixel(file, c) local dt dt = string.format("%c", c) file:write(dt) end function Bitmap:writeComment(fh, ...) local strings = {...} local str = "" local result for _, s in pairs(strings) do str = str .. tostring(s) end result = string.format("# %s\n", str) fh:write(result) end function Bitmap:writeP6(filename) local fh = io.open(filename, 'w') if not fh then error(string.format("failed to open %q for writing", filename)) else fh:write(string.format("P6 %d %d 255\n", self.width, self.height)) self:writeComment(fh, "automatically generated at ", os.date()) for _, row in pairs(self.data) do for _, pixel in pairs(row) do self:writeRawPixel(fh, pixel[1]) self:writeRawPixel(fh, pixel[2]) self:writeRawPixel(fh, pixel[3]) end end end end function Bitmap:fill(x, y, width, height, color) width = (width == nil) and self.width or width height = (height == nil) and self.height or height width = width + x height = height + y for i=y, height do for j=x, width do self:setPixel(j, i, color) end end end function Bitmap:setPixel(x, y, color) if x >= self.width then return false elseif x < 0 then return false elseif y >= self.height then return false elseif y < 0 then return false end self.data[y][x] = color return true end function example_colorful_stripes() local w = 260*2 local h = 260*2 local b = Bitmap.new(w, h) b:setPixel(0, 15, {255,68,0}) for i=1, w do for j=1, h do b:setPixel(i, j, { (i + j * 8) % 256, (j + (255 * i)) % 256, (i * j) % 256 } ); end end return b end example_colorful_stripes():writeP6('p6.ppm')
import java.io.BufferedOutputStream; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.nio.charset.StandardCharsets; public class PPMWriter { public void bitmapToPPM(File file, BasicBitmapStorage bitmap) throws IOException { file.delete(); try (var os = new FileOutputStream(file, true); var bw = new BufferedOutputStream(os)) { var header = String.format("P6\n%d %d\n255\n", bitmap.getWidth(), bitmap.getHeight()); bw.write(header.getBytes(StandardCharsets.US_ASCII)); for (var y = 0; y < bitmap.getHeight(); y++) { for (var x = 0; x < bitmap.getWidth(); x++) { var pixel = bitmap.getPixel(x, y); bw.write(pixel.getRed()); bw.write(pixel.getGreen()); bw.write(pixel.getBlue()); } } } } }
Port the following code from Lua to Python with equivalent syntax and logic.
local array_fill = function(vbegin, vend, value) local t = {} for i=vbegin, vend do t[i] = value end return t end Bitmap = {} Bitmap.__index = Bitmap function Bitmap.new(width, height) local self = {} setmetatable(self, Bitmap) local white = array_fill(0, width, {255, 255, 255}) self.data = array_fill(0, height, white) self.width = width self.height = height return self end function Bitmap:writeRawPixel(file, c) local dt dt = string.format("%c", c) file:write(dt) end function Bitmap:writeComment(fh, ...) local strings = {...} local str = "" local result for _, s in pairs(strings) do str = str .. tostring(s) end result = string.format("# %s\n", str) fh:write(result) end function Bitmap:writeP6(filename) local fh = io.open(filename, 'w') if not fh then error(string.format("failed to open %q for writing", filename)) else fh:write(string.format("P6 %d %d 255\n", self.width, self.height)) self:writeComment(fh, "automatically generated at ", os.date()) for _, row in pairs(self.data) do for _, pixel in pairs(row) do self:writeRawPixel(fh, pixel[1]) self:writeRawPixel(fh, pixel[2]) self:writeRawPixel(fh, pixel[3]) end end end end function Bitmap:fill(x, y, width, height, color) width = (width == nil) and self.width or width height = (height == nil) and self.height or height width = width + x height = height + y for i=y, height do for j=x, width do self:setPixel(j, i, color) end end end function Bitmap:setPixel(x, y, color) if x >= self.width then return false elseif x < 0 then return false elseif y >= self.height then return false elseif y < 0 then return false end self.data[y][x] = color return true end function example_colorful_stripes() local w = 260*2 local h = 260*2 local b = Bitmap.new(w, h) b:setPixel(0, 15, {255,68,0}) for i=1, w do for j=1, h do b:setPixel(i, j, { (i + j * 8) % 256, (j + (255 * i)) % 256, (i * j) % 256 } ); end end return b end example_colorful_stripes():writeP6('p6.ppm')
import io ppmfileout = io.StringIO('') def writeppmp3(self, f): self.writeppm(f, ppmformat='P3') def writeppm(self, f, ppmformat='P6'): assert ppmformat in ['P3', 'P6'], 'Format wrong' magic = ppmformat + '\n' comment = ' maxval = max(max(max(bit) for bit in row) for row in self.map) assert ppmformat == 'P3' or 0 <= maxval < 256, 'R,G,B must fit in a byte' if ppmformat == 'P6': fwrite = lambda s: f.write(bytes(s, 'UTF-8')) maxval = 255 else: fwrite = f.write numsize=len(str(maxval)) fwrite(magic) fwrite(comment) fwrite('%i %i\n%i\n' % (self.width, self.height, maxval)) for h in range(self.height-1, -1, -1): for w in range(self.width): r, g, b = self.get(w, h) if ppmformat == 'P3': fwrite(' %*i %*i %*i' % (numsize, r, numsize, g, numsize, b)) else: fwrite('%c%c%c' % (r, g, b)) if ppmformat == 'P3': fwrite('\n') Bitmap.writeppmp3 = writeppmp3 Bitmap.writeppm = writeppm bitmap = Bitmap(4, 4, black) bitmap.fillrect(1, 0, 1, 2, white) bitmap.set(3, 3, Colour(127, 0, 63)) bitmap.writeppmp3(ppmfileout) print(ppmfileout.getvalue()) ppmfileout = open('tmp.ppm', 'wb') bitmap.writeppm(ppmfileout) ppmfileout.close()
Please provide an equivalent version of this Lua code in VB.
local array_fill = function(vbegin, vend, value) local t = {} for i=vbegin, vend do t[i] = value end return t end Bitmap = {} Bitmap.__index = Bitmap function Bitmap.new(width, height) local self = {} setmetatable(self, Bitmap) local white = array_fill(0, width, {255, 255, 255}) self.data = array_fill(0, height, white) self.width = width self.height = height return self end function Bitmap:writeRawPixel(file, c) local dt dt = string.format("%c", c) file:write(dt) end function Bitmap:writeComment(fh, ...) local strings = {...} local str = "" local result for _, s in pairs(strings) do str = str .. tostring(s) end result = string.format("# %s\n", str) fh:write(result) end function Bitmap:writeP6(filename) local fh = io.open(filename, 'w') if not fh then error(string.format("failed to open %q for writing", filename)) else fh:write(string.format("P6 %d %d 255\n", self.width, self.height)) self:writeComment(fh, "automatically generated at ", os.date()) for _, row in pairs(self.data) do for _, pixel in pairs(row) do self:writeRawPixel(fh, pixel[1]) self:writeRawPixel(fh, pixel[2]) self:writeRawPixel(fh, pixel[3]) end end end end function Bitmap:fill(x, y, width, height, color) width = (width == nil) and self.width or width height = (height == nil) and self.height or height width = width + x height = height + y for i=y, height do for j=x, width do self:setPixel(j, i, color) end end end function Bitmap:setPixel(x, y, color) if x >= self.width then return false elseif x < 0 then return false elseif y >= self.height then return false elseif y < 0 then return false end self.data[y][x] = color return true end function example_colorful_stripes() local w = 260*2 local h = 260*2 local b = Bitmap.new(w, h) b:setPixel(0, 15, {255,68,0}) for i=1, w do for j=1, h do b:setPixel(i, j, { (i + j * 8) % 256, (j + (255 * i)) % 256, (i * j) % 256 } ); end end return b end example_colorful_stripes():writeP6('p6.ppm')
Public Shared Sub SaveRasterBitmapToPpmFile(ByVal rasterBitmap As RasterBitmap, ByVal filepath As String) Dim header As String = String.Format("P6{0}{1}{2}{3}{0}255{0}", vbLf, rasterBitmap.Width, " "c, rasterBitmap.Height) Dim bufferSize As Integer = header.Length + (rasterBitmap.Width * rasterBitmap.Height * 3) Dim bytes(bufferSize - 1) As Byte Buffer.BlockCopy(Encoding.ASCII.GetBytes(header.ToString), 0, bytes, 0, header.Length) Dim index As Integer = header.Length For y As Integer = 0 To rasterBitmap.Height - 1 For x As Integer = 0 To rasterBitmap.Width - 1 Dim color As Rgb = rasterBitmap.GetPixel(x, y) bytes(index) = color.R bytes(index + 1) = color.G bytes(index + 2) = color.B index += 3 Next Next My.Computer.FileSystem.WriteAllBytes(filepath, bytes, False) End Sub
Rewrite the snippet below in Go so it works the same as the original Lua code.
local array_fill = function(vbegin, vend, value) local t = {} for i=vbegin, vend do t[i] = value end return t end Bitmap = {} Bitmap.__index = Bitmap function Bitmap.new(width, height) local self = {} setmetatable(self, Bitmap) local white = array_fill(0, width, {255, 255, 255}) self.data = array_fill(0, height, white) self.width = width self.height = height return self end function Bitmap:writeRawPixel(file, c) local dt dt = string.format("%c", c) file:write(dt) end function Bitmap:writeComment(fh, ...) local strings = {...} local str = "" local result for _, s in pairs(strings) do str = str .. tostring(s) end result = string.format("# %s\n", str) fh:write(result) end function Bitmap:writeP6(filename) local fh = io.open(filename, 'w') if not fh then error(string.format("failed to open %q for writing", filename)) else fh:write(string.format("P6 %d %d 255\n", self.width, self.height)) self:writeComment(fh, "automatically generated at ", os.date()) for _, row in pairs(self.data) do for _, pixel in pairs(row) do self:writeRawPixel(fh, pixel[1]) self:writeRawPixel(fh, pixel[2]) self:writeRawPixel(fh, pixel[3]) end end end end function Bitmap:fill(x, y, width, height, color) width = (width == nil) and self.width or width height = (height == nil) and self.height or height width = width + x height = height + y for i=y, height do for j=x, width do self:setPixel(j, i, color) end end end function Bitmap:setPixel(x, y, color) if x >= self.width then return false elseif x < 0 then return false elseif y >= self.height then return false elseif y < 0 then return false end self.data[y][x] = color return true end function example_colorful_stripes() local w = 260*2 local h = 260*2 local b = Bitmap.new(w, h) b:setPixel(0, 15, {255,68,0}) for i=1, w do for j=1, h do b:setPixel(i, j, { (i + j * 8) % 256, (j + (255 * i)) % 256, (i * j) % 256 } ); end end return b end example_colorful_stripes():writeP6('p6.ppm')
package raster import ( "fmt" "io" "os" ) func (b *Bitmap) WritePpmTo(w io.Writer) (err error) { if _, err = fmt.Fprintln(w, "P6"); err != nil { return } for _, c := range b.Comments { if _, err = fmt.Fprintln(w, c); err != nil { return } } _, err = fmt.Fprintf(w, "%d %d\n255\n", b.cols, b.rows) if err != nil { return } b3 := make([]byte, 3*len(b.px)) n1 := 0 for _, px := range b.px { b3[n1] = px.R b3[n1+1] = px.G b3[n1+2] = px.B n1 += 3 } if _, err = w.Write(b3); err != nil { return } return } func (b *Bitmap) WritePpmFile(fn string) (err error) { var f *os.File if f, err = os.Create(fn); err != nil { return } if err = b.WritePpmTo(f); err != nil { return } return f.Close() }
Maintain the same structure and functionality when rewriting this code in C.
Export["file.ppm",image,"PPM"]
#include <stdlib.h> #include <stdio.h> int main(void) { const int dimx = 800, dimy = 800; int i, j; FILE *fp = fopen("first.ppm", "wb"); (void) fprintf(fp, "P6\n%d %d\n255\n", dimx, dimy); for (j = 0; j < dimy; ++j) { for (i = 0; i < dimx; ++i) { static unsigned char color[3]; color[0] = i % 256; color[1] = j % 256; color[2] = (i * j) % 256; (void) fwrite(color, 1, 3, fp); } } (void) fclose(fp); return EXIT_SUCCESS; }
Write the same algorithm in C# as shown in this Mathematica implementation.
Export["file.ppm",image,"PPM"]
using System; using System.IO; class PPMWriter { public static void WriteBitmapToPPM(string file, Bitmap bitmap) { var writer = new StreamWriter(file); writer.WriteLine("P6"); writer.WriteLine($"{bitmap.Width} {bitmap.Height}"); writer.WriteLine("255"); writer.Close(); var writerB = new BinaryWriter(new FileStream(file, FileMode.Append)); for (int x = 0; x < bitmap.Height; x++) for (int y = 0; y < bitmap.Width; y++) { Color color = bitmap.GetPixel(y, x); writerB.Write(color.R); writerB.Write(color.G); writerB.Write(color.B); } writerB.Close(); } }
Convert this Mathematica block to C++, preserving its control flow and logic.
Export["file.ppm",image,"PPM"]
#include <fstream> int main() { constexpr auto dimx = 800u, dimy = 800u; std::ofstream ofs("first.ppm", ios_base::out | ios_base::binary); ofs << "P6\n" << dimx << ' ' << dimy << "\n255\n"; for (auto j = 0u; j < dimy; ++j) for (auto i = 0u; i < dimx; ++i) ofs << static_cast<char>(i % 256) << static_cast<char>(j % 256) << static_cast<char>((i * j) % 256); }
Convert this Mathematica block to Java, preserving its control flow and logic.
Export["file.ppm",image,"PPM"]
import java.io.BufferedOutputStream; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.nio.charset.StandardCharsets; public class PPMWriter { public void bitmapToPPM(File file, BasicBitmapStorage bitmap) throws IOException { file.delete(); try (var os = new FileOutputStream(file, true); var bw = new BufferedOutputStream(os)) { var header = String.format("P6\n%d %d\n255\n", bitmap.getWidth(), bitmap.getHeight()); bw.write(header.getBytes(StandardCharsets.US_ASCII)); for (var y = 0; y < bitmap.getHeight(); y++) { for (var x = 0; x < bitmap.getWidth(); x++) { var pixel = bitmap.getPixel(x, y); bw.write(pixel.getRed()); bw.write(pixel.getGreen()); bw.write(pixel.getBlue()); } } } } }
Preserve the algorithm and functionality while converting the code from Mathematica to Python.
Export["file.ppm",image,"PPM"]
import io ppmfileout = io.StringIO('') def writeppmp3(self, f): self.writeppm(f, ppmformat='P3') def writeppm(self, f, ppmformat='P6'): assert ppmformat in ['P3', 'P6'], 'Format wrong' magic = ppmformat + '\n' comment = ' maxval = max(max(max(bit) for bit in row) for row in self.map) assert ppmformat == 'P3' or 0 <= maxval < 256, 'R,G,B must fit in a byte' if ppmformat == 'P6': fwrite = lambda s: f.write(bytes(s, 'UTF-8')) maxval = 255 else: fwrite = f.write numsize=len(str(maxval)) fwrite(magic) fwrite(comment) fwrite('%i %i\n%i\n' % (self.width, self.height, maxval)) for h in range(self.height-1, -1, -1): for w in range(self.width): r, g, b = self.get(w, h) if ppmformat == 'P3': fwrite(' %*i %*i %*i' % (numsize, r, numsize, g, numsize, b)) else: fwrite('%c%c%c' % (r, g, b)) if ppmformat == 'P3': fwrite('\n') Bitmap.writeppmp3 = writeppmp3 Bitmap.writeppm = writeppm bitmap = Bitmap(4, 4, black) bitmap.fillrect(1, 0, 1, 2, white) bitmap.set(3, 3, Colour(127, 0, 63)) bitmap.writeppmp3(ppmfileout) print(ppmfileout.getvalue()) ppmfileout = open('tmp.ppm', 'wb') bitmap.writeppm(ppmfileout) ppmfileout.close()
Produce a language-to-language conversion: from Mathematica to VB, same semantics.
Export["file.ppm",image,"PPM"]
Public Shared Sub SaveRasterBitmapToPpmFile(ByVal rasterBitmap As RasterBitmap, ByVal filepath As String) Dim header As String = String.Format("P6{0}{1}{2}{3}{0}255{0}", vbLf, rasterBitmap.Width, " "c, rasterBitmap.Height) Dim bufferSize As Integer = header.Length + (rasterBitmap.Width * rasterBitmap.Height * 3) Dim bytes(bufferSize - 1) As Byte Buffer.BlockCopy(Encoding.ASCII.GetBytes(header.ToString), 0, bytes, 0, header.Length) Dim index As Integer = header.Length For y As Integer = 0 To rasterBitmap.Height - 1 For x As Integer = 0 To rasterBitmap.Width - 1 Dim color As Rgb = rasterBitmap.GetPixel(x, y) bytes(index) = color.R bytes(index + 1) = color.G bytes(index + 2) = color.B index += 3 Next Next My.Computer.FileSystem.WriteAllBytes(filepath, bytes, False) End Sub
Write the same code in Go as shown below in Mathematica.
Export["file.ppm",image,"PPM"]
package raster import ( "fmt" "io" "os" ) func (b *Bitmap) WritePpmTo(w io.Writer) (err error) { if _, err = fmt.Fprintln(w, "P6"); err != nil { return } for _, c := range b.Comments { if _, err = fmt.Fprintln(w, c); err != nil { return } } _, err = fmt.Fprintf(w, "%d %d\n255\n", b.cols, b.rows) if err != nil { return } b3 := make([]byte, 3*len(b.px)) n1 := 0 for _, px := range b.px { b3[n1] = px.R b3[n1+1] = px.G b3[n1+2] = px.B n1 += 3 } if _, err = w.Write(b3); err != nil { return } return } func (b *Bitmap) WritePpmFile(fn string) (err error) { var f *os.File if f, err = os.Create(fn); err != nil { return } if err = b.WritePpmTo(f); err != nil { return } return f.Close() }
Can you help me rewrite this code in C instead of MATLAB, keeping it the same logically?
R=[255,0,0;255,255,0]; G=[0,255,0;255,255,0]; B=[0,0,255;0,0,0]; r = R'; r(:); g = R'; g(:); b = R'; b(:); fid=fopen('p6.ppm','w'); fprintf(fid,'P6\n fwrite(fid,[r,g,b]','uint8'); fclose(fid);
#include <stdlib.h> #include <stdio.h> int main(void) { const int dimx = 800, dimy = 800; int i, j; FILE *fp = fopen("first.ppm", "wb"); (void) fprintf(fp, "P6\n%d %d\n255\n", dimx, dimy); for (j = 0; j < dimy; ++j) { for (i = 0; i < dimx; ++i) { static unsigned char color[3]; color[0] = i % 256; color[1] = j % 256; color[2] = (i * j) % 256; (void) fwrite(color, 1, 3, fp); } } (void) fclose(fp); return EXIT_SUCCESS; }
Port the following code from MATLAB to C# with equivalent syntax and logic.
R=[255,0,0;255,255,0]; G=[0,255,0;255,255,0]; B=[0,0,255;0,0,0]; r = R'; r(:); g = R'; g(:); b = R'; b(:); fid=fopen('p6.ppm','w'); fprintf(fid,'P6\n fwrite(fid,[r,g,b]','uint8'); fclose(fid);
using System; using System.IO; class PPMWriter { public static void WriteBitmapToPPM(string file, Bitmap bitmap) { var writer = new StreamWriter(file); writer.WriteLine("P6"); writer.WriteLine($"{bitmap.Width} {bitmap.Height}"); writer.WriteLine("255"); writer.Close(); var writerB = new BinaryWriter(new FileStream(file, FileMode.Append)); for (int x = 0; x < bitmap.Height; x++) for (int y = 0; y < bitmap.Width; y++) { Color color = bitmap.GetPixel(y, x); writerB.Write(color.R); writerB.Write(color.G); writerB.Write(color.B); } writerB.Close(); } }
Port the provided MATLAB code into C++ while preserving the original functionality.
R=[255,0,0;255,255,0]; G=[0,255,0;255,255,0]; B=[0,0,255;0,0,0]; r = R'; r(:); g = R'; g(:); b = R'; b(:); fid=fopen('p6.ppm','w'); fprintf(fid,'P6\n fwrite(fid,[r,g,b]','uint8'); fclose(fid);
#include <fstream> int main() { constexpr auto dimx = 800u, dimy = 800u; std::ofstream ofs("first.ppm", ios_base::out | ios_base::binary); ofs << "P6\n" << dimx << ' ' << dimy << "\n255\n"; for (auto j = 0u; j < dimy; ++j) for (auto i = 0u; i < dimx; ++i) ofs << static_cast<char>(i % 256) << static_cast<char>(j % 256) << static_cast<char>((i * j) % 256); }
Change the programming language of this snippet from MATLAB to Java without modifying what it does.
R=[255,0,0;255,255,0]; G=[0,255,0;255,255,0]; B=[0,0,255;0,0,0]; r = R'; r(:); g = R'; g(:); b = R'; b(:); fid=fopen('p6.ppm','w'); fprintf(fid,'P6\n fwrite(fid,[r,g,b]','uint8'); fclose(fid);
import java.io.BufferedOutputStream; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.nio.charset.StandardCharsets; public class PPMWriter { public void bitmapToPPM(File file, BasicBitmapStorage bitmap) throws IOException { file.delete(); try (var os = new FileOutputStream(file, true); var bw = new BufferedOutputStream(os)) { var header = String.format("P6\n%d %d\n255\n", bitmap.getWidth(), bitmap.getHeight()); bw.write(header.getBytes(StandardCharsets.US_ASCII)); for (var y = 0; y < bitmap.getHeight(); y++) { for (var x = 0; x < bitmap.getWidth(); x++) { var pixel = bitmap.getPixel(x, y); bw.write(pixel.getRed()); bw.write(pixel.getGreen()); bw.write(pixel.getBlue()); } } } } }
Convert the following code from MATLAB to Python, ensuring the logic remains intact.
R=[255,0,0;255,255,0]; G=[0,255,0;255,255,0]; B=[0,0,255;0,0,0]; r = R'; r(:); g = R'; g(:); b = R'; b(:); fid=fopen('p6.ppm','w'); fprintf(fid,'P6\n fwrite(fid,[r,g,b]','uint8'); fclose(fid);
import io ppmfileout = io.StringIO('') def writeppmp3(self, f): self.writeppm(f, ppmformat='P3') def writeppm(self, f, ppmformat='P6'): assert ppmformat in ['P3', 'P6'], 'Format wrong' magic = ppmformat + '\n' comment = ' maxval = max(max(max(bit) for bit in row) for row in self.map) assert ppmformat == 'P3' or 0 <= maxval < 256, 'R,G,B must fit in a byte' if ppmformat == 'P6': fwrite = lambda s: f.write(bytes(s, 'UTF-8')) maxval = 255 else: fwrite = f.write numsize=len(str(maxval)) fwrite(magic) fwrite(comment) fwrite('%i %i\n%i\n' % (self.width, self.height, maxval)) for h in range(self.height-1, -1, -1): for w in range(self.width): r, g, b = self.get(w, h) if ppmformat == 'P3': fwrite(' %*i %*i %*i' % (numsize, r, numsize, g, numsize, b)) else: fwrite('%c%c%c' % (r, g, b)) if ppmformat == 'P3': fwrite('\n') Bitmap.writeppmp3 = writeppmp3 Bitmap.writeppm = writeppm bitmap = Bitmap(4, 4, black) bitmap.fillrect(1, 0, 1, 2, white) bitmap.set(3, 3, Colour(127, 0, 63)) bitmap.writeppmp3(ppmfileout) print(ppmfileout.getvalue()) ppmfileout = open('tmp.ppm', 'wb') bitmap.writeppm(ppmfileout) ppmfileout.close()
Keep all operations the same but rewrite the snippet in VB.
R=[255,0,0;255,255,0]; G=[0,255,0;255,255,0]; B=[0,0,255;0,0,0]; r = R'; r(:); g = R'; g(:); b = R'; b(:); fid=fopen('p6.ppm','w'); fprintf(fid,'P6\n fwrite(fid,[r,g,b]','uint8'); fclose(fid);
Public Shared Sub SaveRasterBitmapToPpmFile(ByVal rasterBitmap As RasterBitmap, ByVal filepath As String) Dim header As String = String.Format("P6{0}{1}{2}{3}{0}255{0}", vbLf, rasterBitmap.Width, " "c, rasterBitmap.Height) Dim bufferSize As Integer = header.Length + (rasterBitmap.Width * rasterBitmap.Height * 3) Dim bytes(bufferSize - 1) As Byte Buffer.BlockCopy(Encoding.ASCII.GetBytes(header.ToString), 0, bytes, 0, header.Length) Dim index As Integer = header.Length For y As Integer = 0 To rasterBitmap.Height - 1 For x As Integer = 0 To rasterBitmap.Width - 1 Dim color As Rgb = rasterBitmap.GetPixel(x, y) bytes(index) = color.R bytes(index + 1) = color.G bytes(index + 2) = color.B index += 3 Next Next My.Computer.FileSystem.WriteAllBytes(filepath, bytes, False) End Sub
Port the following code from MATLAB to Go with equivalent syntax and logic.
R=[255,0,0;255,255,0]; G=[0,255,0;255,255,0]; B=[0,0,255;0,0,0]; r = R'; r(:); g = R'; g(:); b = R'; b(:); fid=fopen('p6.ppm','w'); fprintf(fid,'P6\n fwrite(fid,[r,g,b]','uint8'); fclose(fid);
package raster import ( "fmt" "io" "os" ) func (b *Bitmap) WritePpmTo(w io.Writer) (err error) { if _, err = fmt.Fprintln(w, "P6"); err != nil { return } for _, c := range b.Comments { if _, err = fmt.Fprintln(w, c); err != nil { return } } _, err = fmt.Fprintf(w, "%d %d\n255\n", b.cols, b.rows) if err != nil { return } b3 := make([]byte, 3*len(b.px)) n1 := 0 for _, px := range b.px { b3[n1] = px.R b3[n1+1] = px.G b3[n1+2] = px.B n1 += 3 } if _, err = w.Write(b3); err != nil { return } return } func (b *Bitmap) WritePpmFile(fn string) (err error) { var f *os.File if f, err = os.Create(fn); err != nil { return } if err = b.WritePpmTo(f); err != nil { return } return f.Close() }
Convert this Nim block to C, preserving its control flow and logic.
import bitmap import streams proc writePPM*(img: Image, stream: Stream) = stream.writeLine("P6 ", $img.w, " ", $img.h, " 255") for x, y in img.indices: stream.write(chr(img[x, y].r)) stream.write(chr(img[x, y].g)) stream.write(chr(img[x, y].b)) proc writePPM*(img: Image; filename: string) = var file = openFileStream(filename, fmWrite) img.writePPM(file) file.close() when isMainModule: var image = newImage(100, 50) image.fill(color(255, 0, 0)) for row in 10..20: for col in 0..<image.w: image[col, row] = color(0, 255, 0) for row in 30..40: for col in 0..<image.w: image[col, row] = color(0, 0, 255) image.writePPM("output.ppm")
#include <stdlib.h> #include <stdio.h> int main(void) { const int dimx = 800, dimy = 800; int i, j; FILE *fp = fopen("first.ppm", "wb"); (void) fprintf(fp, "P6\n%d %d\n255\n", dimx, dimy); for (j = 0; j < dimy; ++j) { for (i = 0; i < dimx; ++i) { static unsigned char color[3]; color[0] = i % 256; color[1] = j % 256; color[2] = (i * j) % 256; (void) fwrite(color, 1, 3, fp); } } (void) fclose(fp); return EXIT_SUCCESS; }
Produce a language-to-language conversion: from Nim to C#, same semantics.
import bitmap import streams proc writePPM*(img: Image, stream: Stream) = stream.writeLine("P6 ", $img.w, " ", $img.h, " 255") for x, y in img.indices: stream.write(chr(img[x, y].r)) stream.write(chr(img[x, y].g)) stream.write(chr(img[x, y].b)) proc writePPM*(img: Image; filename: string) = var file = openFileStream(filename, fmWrite) img.writePPM(file) file.close() when isMainModule: var image = newImage(100, 50) image.fill(color(255, 0, 0)) for row in 10..20: for col in 0..<image.w: image[col, row] = color(0, 255, 0) for row in 30..40: for col in 0..<image.w: image[col, row] = color(0, 0, 255) image.writePPM("output.ppm")
using System; using System.IO; class PPMWriter { public static void WriteBitmapToPPM(string file, Bitmap bitmap) { var writer = new StreamWriter(file); writer.WriteLine("P6"); writer.WriteLine($"{bitmap.Width} {bitmap.Height}"); writer.WriteLine("255"); writer.Close(); var writerB = new BinaryWriter(new FileStream(file, FileMode.Append)); for (int x = 0; x < bitmap.Height; x++) for (int y = 0; y < bitmap.Width; y++) { Color color = bitmap.GetPixel(y, x); writerB.Write(color.R); writerB.Write(color.G); writerB.Write(color.B); } writerB.Close(); } }
Change the following Nim code into C++ without altering its purpose.
import bitmap import streams proc writePPM*(img: Image, stream: Stream) = stream.writeLine("P6 ", $img.w, " ", $img.h, " 255") for x, y in img.indices: stream.write(chr(img[x, y].r)) stream.write(chr(img[x, y].g)) stream.write(chr(img[x, y].b)) proc writePPM*(img: Image; filename: string) = var file = openFileStream(filename, fmWrite) img.writePPM(file) file.close() when isMainModule: var image = newImage(100, 50) image.fill(color(255, 0, 0)) for row in 10..20: for col in 0..<image.w: image[col, row] = color(0, 255, 0) for row in 30..40: for col in 0..<image.w: image[col, row] = color(0, 0, 255) image.writePPM("output.ppm")
#include <fstream> int main() { constexpr auto dimx = 800u, dimy = 800u; std::ofstream ofs("first.ppm", ios_base::out | ios_base::binary); ofs << "P6\n" << dimx << ' ' << dimy << "\n255\n"; for (auto j = 0u; j < dimy; ++j) for (auto i = 0u; i < dimx; ++i) ofs << static_cast<char>(i % 256) << static_cast<char>(j % 256) << static_cast<char>((i * j) % 256); }
Port the following code from Nim to Java with equivalent syntax and logic.
import bitmap import streams proc writePPM*(img: Image, stream: Stream) = stream.writeLine("P6 ", $img.w, " ", $img.h, " 255") for x, y in img.indices: stream.write(chr(img[x, y].r)) stream.write(chr(img[x, y].g)) stream.write(chr(img[x, y].b)) proc writePPM*(img: Image; filename: string) = var file = openFileStream(filename, fmWrite) img.writePPM(file) file.close() when isMainModule: var image = newImage(100, 50) image.fill(color(255, 0, 0)) for row in 10..20: for col in 0..<image.w: image[col, row] = color(0, 255, 0) for row in 30..40: for col in 0..<image.w: image[col, row] = color(0, 0, 255) image.writePPM("output.ppm")
import java.io.BufferedOutputStream; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.nio.charset.StandardCharsets; public class PPMWriter { public void bitmapToPPM(File file, BasicBitmapStorage bitmap) throws IOException { file.delete(); try (var os = new FileOutputStream(file, true); var bw = new BufferedOutputStream(os)) { var header = String.format("P6\n%d %d\n255\n", bitmap.getWidth(), bitmap.getHeight()); bw.write(header.getBytes(StandardCharsets.US_ASCII)); for (var y = 0; y < bitmap.getHeight(); y++) { for (var x = 0; x < bitmap.getWidth(); x++) { var pixel = bitmap.getPixel(x, y); bw.write(pixel.getRed()); bw.write(pixel.getGreen()); bw.write(pixel.getBlue()); } } } } }
Can you help me rewrite this code in Python instead of Nim, keeping it the same logically?
import bitmap import streams proc writePPM*(img: Image, stream: Stream) = stream.writeLine("P6 ", $img.w, " ", $img.h, " 255") for x, y in img.indices: stream.write(chr(img[x, y].r)) stream.write(chr(img[x, y].g)) stream.write(chr(img[x, y].b)) proc writePPM*(img: Image; filename: string) = var file = openFileStream(filename, fmWrite) img.writePPM(file) file.close() when isMainModule: var image = newImage(100, 50) image.fill(color(255, 0, 0)) for row in 10..20: for col in 0..<image.w: image[col, row] = color(0, 255, 0) for row in 30..40: for col in 0..<image.w: image[col, row] = color(0, 0, 255) image.writePPM("output.ppm")
import io ppmfileout = io.StringIO('') def writeppmp3(self, f): self.writeppm(f, ppmformat='P3') def writeppm(self, f, ppmformat='P6'): assert ppmformat in ['P3', 'P6'], 'Format wrong' magic = ppmformat + '\n' comment = ' maxval = max(max(max(bit) for bit in row) for row in self.map) assert ppmformat == 'P3' or 0 <= maxval < 256, 'R,G,B must fit in a byte' if ppmformat == 'P6': fwrite = lambda s: f.write(bytes(s, 'UTF-8')) maxval = 255 else: fwrite = f.write numsize=len(str(maxval)) fwrite(magic) fwrite(comment) fwrite('%i %i\n%i\n' % (self.width, self.height, maxval)) for h in range(self.height-1, -1, -1): for w in range(self.width): r, g, b = self.get(w, h) if ppmformat == 'P3': fwrite(' %*i %*i %*i' % (numsize, r, numsize, g, numsize, b)) else: fwrite('%c%c%c' % (r, g, b)) if ppmformat == 'P3': fwrite('\n') Bitmap.writeppmp3 = writeppmp3 Bitmap.writeppm = writeppm bitmap = Bitmap(4, 4, black) bitmap.fillrect(1, 0, 1, 2, white) bitmap.set(3, 3, Colour(127, 0, 63)) bitmap.writeppmp3(ppmfileout) print(ppmfileout.getvalue()) ppmfileout = open('tmp.ppm', 'wb') bitmap.writeppm(ppmfileout) ppmfileout.close()
Write the same code in VB as shown below in Nim.
import bitmap import streams proc writePPM*(img: Image, stream: Stream) = stream.writeLine("P6 ", $img.w, " ", $img.h, " 255") for x, y in img.indices: stream.write(chr(img[x, y].r)) stream.write(chr(img[x, y].g)) stream.write(chr(img[x, y].b)) proc writePPM*(img: Image; filename: string) = var file = openFileStream(filename, fmWrite) img.writePPM(file) file.close() when isMainModule: var image = newImage(100, 50) image.fill(color(255, 0, 0)) for row in 10..20: for col in 0..<image.w: image[col, row] = color(0, 255, 0) for row in 30..40: for col in 0..<image.w: image[col, row] = color(0, 0, 255) image.writePPM("output.ppm")
Public Shared Sub SaveRasterBitmapToPpmFile(ByVal rasterBitmap As RasterBitmap, ByVal filepath As String) Dim header As String = String.Format("P6{0}{1}{2}{3}{0}255{0}", vbLf, rasterBitmap.Width, " "c, rasterBitmap.Height) Dim bufferSize As Integer = header.Length + (rasterBitmap.Width * rasterBitmap.Height * 3) Dim bytes(bufferSize - 1) As Byte Buffer.BlockCopy(Encoding.ASCII.GetBytes(header.ToString), 0, bytes, 0, header.Length) Dim index As Integer = header.Length For y As Integer = 0 To rasterBitmap.Height - 1 For x As Integer = 0 To rasterBitmap.Width - 1 Dim color As Rgb = rasterBitmap.GetPixel(x, y) bytes(index) = color.R bytes(index + 1) = color.G bytes(index + 2) = color.B index += 3 Next Next My.Computer.FileSystem.WriteAllBytes(filepath, bytes, False) End Sub
Rewrite this program in Go while keeping its functionality equivalent to the Nim version.
import bitmap import streams proc writePPM*(img: Image, stream: Stream) = stream.writeLine("P6 ", $img.w, " ", $img.h, " 255") for x, y in img.indices: stream.write(chr(img[x, y].r)) stream.write(chr(img[x, y].g)) stream.write(chr(img[x, y].b)) proc writePPM*(img: Image; filename: string) = var file = openFileStream(filename, fmWrite) img.writePPM(file) file.close() when isMainModule: var image = newImage(100, 50) image.fill(color(255, 0, 0)) for row in 10..20: for col in 0..<image.w: image[col, row] = color(0, 255, 0) for row in 30..40: for col in 0..<image.w: image[col, row] = color(0, 0, 255) image.writePPM("output.ppm")
package raster import ( "fmt" "io" "os" ) func (b *Bitmap) WritePpmTo(w io.Writer) (err error) { if _, err = fmt.Fprintln(w, "P6"); err != nil { return } for _, c := range b.Comments { if _, err = fmt.Fprintln(w, c); err != nil { return } } _, err = fmt.Fprintf(w, "%d %d\n255\n", b.cols, b.rows) if err != nil { return } b3 := make([]byte, 3*len(b.px)) n1 := 0 for _, px := range b.px { b3[n1] = px.R b3[n1+1] = px.G b3[n1+2] = px.B n1 += 3 } if _, err = w.Write(b3); err != nil { return } return } func (b *Bitmap) WritePpmFile(fn string) (err error) { var f *os.File if f, err = os.Create(fn); err != nil { return } if err = b.WritePpmTo(f); err != nil { return } return f.Close() }
Produce a language-to-language conversion: from OCaml to C, same semantics.
let output_ppm ~oc ~img:(_, r_channel, g_channel, b_channel) = let width = Bigarray.Array2.dim1 r_channel and height = Bigarray.Array2.dim2 r_channel in Printf.fprintf oc "P6\n%d %d\n255\n" width height; for y = 0 to pred height do for x = 0 to pred width do output_char oc (char_of_int r_channel.{x,y}); output_char oc (char_of_int g_channel.{x,y}); output_char oc (char_of_int b_channel.{x,y}); done; done; output_char oc '\n'; flush oc; ;;
#include <stdlib.h> #include <stdio.h> int main(void) { const int dimx = 800, dimy = 800; int i, j; FILE *fp = fopen("first.ppm", "wb"); (void) fprintf(fp, "P6\n%d %d\n255\n", dimx, dimy); for (j = 0; j < dimy; ++j) { for (i = 0; i < dimx; ++i) { static unsigned char color[3]; color[0] = i % 256; color[1] = j % 256; color[2] = (i * j) % 256; (void) fwrite(color, 1, 3, fp); } } (void) fclose(fp); return EXIT_SUCCESS; }
Translate this program into C# but keep the logic exactly as in OCaml.
let output_ppm ~oc ~img:(_, r_channel, g_channel, b_channel) = let width = Bigarray.Array2.dim1 r_channel and height = Bigarray.Array2.dim2 r_channel in Printf.fprintf oc "P6\n%d %d\n255\n" width height; for y = 0 to pred height do for x = 0 to pred width do output_char oc (char_of_int r_channel.{x,y}); output_char oc (char_of_int g_channel.{x,y}); output_char oc (char_of_int b_channel.{x,y}); done; done; output_char oc '\n'; flush oc; ;;
using System; using System.IO; class PPMWriter { public static void WriteBitmapToPPM(string file, Bitmap bitmap) { var writer = new StreamWriter(file); writer.WriteLine("P6"); writer.WriteLine($"{bitmap.Width} {bitmap.Height}"); writer.WriteLine("255"); writer.Close(); var writerB = new BinaryWriter(new FileStream(file, FileMode.Append)); for (int x = 0; x < bitmap.Height; x++) for (int y = 0; y < bitmap.Width; y++) { Color color = bitmap.GetPixel(y, x); writerB.Write(color.R); writerB.Write(color.G); writerB.Write(color.B); } writerB.Close(); } }
Write the same algorithm in C++ as shown in this OCaml implementation.
let output_ppm ~oc ~img:(_, r_channel, g_channel, b_channel) = let width = Bigarray.Array2.dim1 r_channel and height = Bigarray.Array2.dim2 r_channel in Printf.fprintf oc "P6\n%d %d\n255\n" width height; for y = 0 to pred height do for x = 0 to pred width do output_char oc (char_of_int r_channel.{x,y}); output_char oc (char_of_int g_channel.{x,y}); output_char oc (char_of_int b_channel.{x,y}); done; done; output_char oc '\n'; flush oc; ;;
#include <fstream> int main() { constexpr auto dimx = 800u, dimy = 800u; std::ofstream ofs("first.ppm", ios_base::out | ios_base::binary); ofs << "P6\n" << dimx << ' ' << dimy << "\n255\n"; for (auto j = 0u; j < dimy; ++j) for (auto i = 0u; i < dimx; ++i) ofs << static_cast<char>(i % 256) << static_cast<char>(j % 256) << static_cast<char>((i * j) % 256); }
Ensure the translated Java code behaves exactly like the original OCaml snippet.
let output_ppm ~oc ~img:(_, r_channel, g_channel, b_channel) = let width = Bigarray.Array2.dim1 r_channel and height = Bigarray.Array2.dim2 r_channel in Printf.fprintf oc "P6\n%d %d\n255\n" width height; for y = 0 to pred height do for x = 0 to pred width do output_char oc (char_of_int r_channel.{x,y}); output_char oc (char_of_int g_channel.{x,y}); output_char oc (char_of_int b_channel.{x,y}); done; done; output_char oc '\n'; flush oc; ;;
import java.io.BufferedOutputStream; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.nio.charset.StandardCharsets; public class PPMWriter { public void bitmapToPPM(File file, BasicBitmapStorage bitmap) throws IOException { file.delete(); try (var os = new FileOutputStream(file, true); var bw = new BufferedOutputStream(os)) { var header = String.format("P6\n%d %d\n255\n", bitmap.getWidth(), bitmap.getHeight()); bw.write(header.getBytes(StandardCharsets.US_ASCII)); for (var y = 0; y < bitmap.getHeight(); y++) { for (var x = 0; x < bitmap.getWidth(); x++) { var pixel = bitmap.getPixel(x, y); bw.write(pixel.getRed()); bw.write(pixel.getGreen()); bw.write(pixel.getBlue()); } } } } }
Port the following code from OCaml to Python with equivalent syntax and logic.
let output_ppm ~oc ~img:(_, r_channel, g_channel, b_channel) = let width = Bigarray.Array2.dim1 r_channel and height = Bigarray.Array2.dim2 r_channel in Printf.fprintf oc "P6\n%d %d\n255\n" width height; for y = 0 to pred height do for x = 0 to pred width do output_char oc (char_of_int r_channel.{x,y}); output_char oc (char_of_int g_channel.{x,y}); output_char oc (char_of_int b_channel.{x,y}); done; done; output_char oc '\n'; flush oc; ;;
import io ppmfileout = io.StringIO('') def writeppmp3(self, f): self.writeppm(f, ppmformat='P3') def writeppm(self, f, ppmformat='P6'): assert ppmformat in ['P3', 'P6'], 'Format wrong' magic = ppmformat + '\n' comment = ' maxval = max(max(max(bit) for bit in row) for row in self.map) assert ppmformat == 'P3' or 0 <= maxval < 256, 'R,G,B must fit in a byte' if ppmformat == 'P6': fwrite = lambda s: f.write(bytes(s, 'UTF-8')) maxval = 255 else: fwrite = f.write numsize=len(str(maxval)) fwrite(magic) fwrite(comment) fwrite('%i %i\n%i\n' % (self.width, self.height, maxval)) for h in range(self.height-1, -1, -1): for w in range(self.width): r, g, b = self.get(w, h) if ppmformat == 'P3': fwrite(' %*i %*i %*i' % (numsize, r, numsize, g, numsize, b)) else: fwrite('%c%c%c' % (r, g, b)) if ppmformat == 'P3': fwrite('\n') Bitmap.writeppmp3 = writeppmp3 Bitmap.writeppm = writeppm bitmap = Bitmap(4, 4, black) bitmap.fillrect(1, 0, 1, 2, white) bitmap.set(3, 3, Colour(127, 0, 63)) bitmap.writeppmp3(ppmfileout) print(ppmfileout.getvalue()) ppmfileout = open('tmp.ppm', 'wb') bitmap.writeppm(ppmfileout) ppmfileout.close()
Write the same code in VB as shown below in OCaml.
let output_ppm ~oc ~img:(_, r_channel, g_channel, b_channel) = let width = Bigarray.Array2.dim1 r_channel and height = Bigarray.Array2.dim2 r_channel in Printf.fprintf oc "P6\n%d %d\n255\n" width height; for y = 0 to pred height do for x = 0 to pred width do output_char oc (char_of_int r_channel.{x,y}); output_char oc (char_of_int g_channel.{x,y}); output_char oc (char_of_int b_channel.{x,y}); done; done; output_char oc '\n'; flush oc; ;;
Public Shared Sub SaveRasterBitmapToPpmFile(ByVal rasterBitmap As RasterBitmap, ByVal filepath As String) Dim header As String = String.Format("P6{0}{1}{2}{3}{0}255{0}", vbLf, rasterBitmap.Width, " "c, rasterBitmap.Height) Dim bufferSize As Integer = header.Length + (rasterBitmap.Width * rasterBitmap.Height * 3) Dim bytes(bufferSize - 1) As Byte Buffer.BlockCopy(Encoding.ASCII.GetBytes(header.ToString), 0, bytes, 0, header.Length) Dim index As Integer = header.Length For y As Integer = 0 To rasterBitmap.Height - 1 For x As Integer = 0 To rasterBitmap.Width - 1 Dim color As Rgb = rasterBitmap.GetPixel(x, y) bytes(index) = color.R bytes(index + 1) = color.G bytes(index + 2) = color.B index += 3 Next Next My.Computer.FileSystem.WriteAllBytes(filepath, bytes, False) End Sub
Can you help me rewrite this code in Go instead of OCaml, keeping it the same logically?
let output_ppm ~oc ~img:(_, r_channel, g_channel, b_channel) = let width = Bigarray.Array2.dim1 r_channel and height = Bigarray.Array2.dim2 r_channel in Printf.fprintf oc "P6\n%d %d\n255\n" width height; for y = 0 to pred height do for x = 0 to pred width do output_char oc (char_of_int r_channel.{x,y}); output_char oc (char_of_int g_channel.{x,y}); output_char oc (char_of_int b_channel.{x,y}); done; done; output_char oc '\n'; flush oc; ;;
package raster import ( "fmt" "io" "os" ) func (b *Bitmap) WritePpmTo(w io.Writer) (err error) { if _, err = fmt.Fprintln(w, "P6"); err != nil { return } for _, c := range b.Comments { if _, err = fmt.Fprintln(w, c); err != nil { return } } _, err = fmt.Fprintf(w, "%d %d\n255\n", b.cols, b.rows) if err != nil { return } b3 := make([]byte, 3*len(b.px)) n1 := 0 for _, px := range b.px { b3[n1] = px.R b3[n1+1] = px.G b3[n1+2] = px.B n1 += 3 } if _, err = w.Write(b3); err != nil { return } return } func (b *Bitmap) WritePpmFile(fn string) (err error) { var f *os.File if f, err = os.Create(fn); err != nil { return } if err = b.WritePpmTo(f); err != nil { return } return f.Close() }
Rewrite this program in C while keeping its functionality equivalent to the Perl version.
use Imager; $image = Imager->new(xsize => 200, ysize => 200); $image->box(filled => 1, color => red); $image->box(filled => 1, color => black, xmin => 50, ymin => 50, xmax => 150, ymax => 150); $image->write(file => 'bitmap.ppm') or die $image->errstr;
#include <stdlib.h> #include <stdio.h> int main(void) { const int dimx = 800, dimy = 800; int i, j; FILE *fp = fopen("first.ppm", "wb"); (void) fprintf(fp, "P6\n%d %d\n255\n", dimx, dimy); for (j = 0; j < dimy; ++j) { for (i = 0; i < dimx; ++i) { static unsigned char color[3]; color[0] = i % 256; color[1] = j % 256; color[2] = (i * j) % 256; (void) fwrite(color, 1, 3, fp); } } (void) fclose(fp); return EXIT_SUCCESS; }
Can you help me rewrite this code in C# instead of Perl, keeping it the same logically?
use Imager; $image = Imager->new(xsize => 200, ysize => 200); $image->box(filled => 1, color => red); $image->box(filled => 1, color => black, xmin => 50, ymin => 50, xmax => 150, ymax => 150); $image->write(file => 'bitmap.ppm') or die $image->errstr;
using System; using System.IO; class PPMWriter { public static void WriteBitmapToPPM(string file, Bitmap bitmap) { var writer = new StreamWriter(file); writer.WriteLine("P6"); writer.WriteLine($"{bitmap.Width} {bitmap.Height}"); writer.WriteLine("255"); writer.Close(); var writerB = new BinaryWriter(new FileStream(file, FileMode.Append)); for (int x = 0; x < bitmap.Height; x++) for (int y = 0; y < bitmap.Width; y++) { Color color = bitmap.GetPixel(y, x); writerB.Write(color.R); writerB.Write(color.G); writerB.Write(color.B); } writerB.Close(); } }
Can you help me rewrite this code in C++ instead of Perl, keeping it the same logically?
use Imager; $image = Imager->new(xsize => 200, ysize => 200); $image->box(filled => 1, color => red); $image->box(filled => 1, color => black, xmin => 50, ymin => 50, xmax => 150, ymax => 150); $image->write(file => 'bitmap.ppm') or die $image->errstr;
#include <fstream> int main() { constexpr auto dimx = 800u, dimy = 800u; std::ofstream ofs("first.ppm", ios_base::out | ios_base::binary); ofs << "P6\n" << dimx << ' ' << dimy << "\n255\n"; for (auto j = 0u; j < dimy; ++j) for (auto i = 0u; i < dimx; ++i) ofs << static_cast<char>(i % 256) << static_cast<char>(j % 256) << static_cast<char>((i * j) % 256); }
Write a version of this Perl function in Java with identical behavior.
use Imager; $image = Imager->new(xsize => 200, ysize => 200); $image->box(filled => 1, color => red); $image->box(filled => 1, color => black, xmin => 50, ymin => 50, xmax => 150, ymax => 150); $image->write(file => 'bitmap.ppm') or die $image->errstr;
import java.io.BufferedOutputStream; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.nio.charset.StandardCharsets; public class PPMWriter { public void bitmapToPPM(File file, BasicBitmapStorage bitmap) throws IOException { file.delete(); try (var os = new FileOutputStream(file, true); var bw = new BufferedOutputStream(os)) { var header = String.format("P6\n%d %d\n255\n", bitmap.getWidth(), bitmap.getHeight()); bw.write(header.getBytes(StandardCharsets.US_ASCII)); for (var y = 0; y < bitmap.getHeight(); y++) { for (var x = 0; x < bitmap.getWidth(); x++) { var pixel = bitmap.getPixel(x, y); bw.write(pixel.getRed()); bw.write(pixel.getGreen()); bw.write(pixel.getBlue()); } } } } }
Change the following Perl code into Python without altering its purpose.
use Imager; $image = Imager->new(xsize => 200, ysize => 200); $image->box(filled => 1, color => red); $image->box(filled => 1, color => black, xmin => 50, ymin => 50, xmax => 150, ymax => 150); $image->write(file => 'bitmap.ppm') or die $image->errstr;
import io ppmfileout = io.StringIO('') def writeppmp3(self, f): self.writeppm(f, ppmformat='P3') def writeppm(self, f, ppmformat='P6'): assert ppmformat in ['P3', 'P6'], 'Format wrong' magic = ppmformat + '\n' comment = ' maxval = max(max(max(bit) for bit in row) for row in self.map) assert ppmformat == 'P3' or 0 <= maxval < 256, 'R,G,B must fit in a byte' if ppmformat == 'P6': fwrite = lambda s: f.write(bytes(s, 'UTF-8')) maxval = 255 else: fwrite = f.write numsize=len(str(maxval)) fwrite(magic) fwrite(comment) fwrite('%i %i\n%i\n' % (self.width, self.height, maxval)) for h in range(self.height-1, -1, -1): for w in range(self.width): r, g, b = self.get(w, h) if ppmformat == 'P3': fwrite(' %*i %*i %*i' % (numsize, r, numsize, g, numsize, b)) else: fwrite('%c%c%c' % (r, g, b)) if ppmformat == 'P3': fwrite('\n') Bitmap.writeppmp3 = writeppmp3 Bitmap.writeppm = writeppm bitmap = Bitmap(4, 4, black) bitmap.fillrect(1, 0, 1, 2, white) bitmap.set(3, 3, Colour(127, 0, 63)) bitmap.writeppmp3(ppmfileout) print(ppmfileout.getvalue()) ppmfileout = open('tmp.ppm', 'wb') bitmap.writeppm(ppmfileout) ppmfileout.close()
Generate an equivalent VB version of this Perl code.
use Imager; $image = Imager->new(xsize => 200, ysize => 200); $image->box(filled => 1, color => red); $image->box(filled => 1, color => black, xmin => 50, ymin => 50, xmax => 150, ymax => 150); $image->write(file => 'bitmap.ppm') or die $image->errstr;
Public Shared Sub SaveRasterBitmapToPpmFile(ByVal rasterBitmap As RasterBitmap, ByVal filepath As String) Dim header As String = String.Format("P6{0}{1}{2}{3}{0}255{0}", vbLf, rasterBitmap.Width, " "c, rasterBitmap.Height) Dim bufferSize As Integer = header.Length + (rasterBitmap.Width * rasterBitmap.Height * 3) Dim bytes(bufferSize - 1) As Byte Buffer.BlockCopy(Encoding.ASCII.GetBytes(header.ToString), 0, bytes, 0, header.Length) Dim index As Integer = header.Length For y As Integer = 0 To rasterBitmap.Height - 1 For x As Integer = 0 To rasterBitmap.Width - 1 Dim color As Rgb = rasterBitmap.GetPixel(x, y) bytes(index) = color.R bytes(index + 1) = color.G bytes(index + 2) = color.B index += 3 Next Next My.Computer.FileSystem.WriteAllBytes(filepath, bytes, False) End Sub
Produce a functionally identical Go code for the snippet given in Perl.
use Imager; $image = Imager->new(xsize => 200, ysize => 200); $image->box(filled => 1, color => red); $image->box(filled => 1, color => black, xmin => 50, ymin => 50, xmax => 150, ymax => 150); $image->write(file => 'bitmap.ppm') or die $image->errstr;
package raster import ( "fmt" "io" "os" ) func (b *Bitmap) WritePpmTo(w io.Writer) (err error) { if _, err = fmt.Fprintln(w, "P6"); err != nil { return } for _, c := range b.Comments { if _, err = fmt.Fprintln(w, c); err != nil { return } } _, err = fmt.Fprintf(w, "%d %d\n255\n", b.cols, b.rows) if err != nil { return } b3 := make([]byte, 3*len(b.px)) n1 := 0 for _, px := range b.px { b3[n1] = px.R b3[n1+1] = px.G b3[n1+2] = px.B n1 += 3 } if _, err = w.Write(b3); err != nil { return } return } func (b *Bitmap) WritePpmFile(fn string) (err error) { var f *os.File if f, err = os.Create(fn); err != nil { return } if err = b.WritePpmTo(f); err != nil { return } return f.Close() }
Transform the following R implementation into C, maintaining the same output and logic.
library(pixmap) pixmap::write.pnm write.pnm(theimage, filename)
#include <stdlib.h> #include <stdio.h> int main(void) { const int dimx = 800, dimy = 800; int i, j; FILE *fp = fopen("first.ppm", "wb"); (void) fprintf(fp, "P6\n%d %d\n255\n", dimx, dimy); for (j = 0; j < dimy; ++j) { for (i = 0; i < dimx; ++i) { static unsigned char color[3]; color[0] = i % 256; color[1] = j % 256; color[2] = (i * j) % 256; (void) fwrite(color, 1, 3, fp); } } (void) fclose(fp); return EXIT_SUCCESS; }
Write the same algorithm in C# as shown in this R implementation.
library(pixmap) pixmap::write.pnm write.pnm(theimage, filename)
using System; using System.IO; class PPMWriter { public static void WriteBitmapToPPM(string file, Bitmap bitmap) { var writer = new StreamWriter(file); writer.WriteLine("P6"); writer.WriteLine($"{bitmap.Width} {bitmap.Height}"); writer.WriteLine("255"); writer.Close(); var writerB = new BinaryWriter(new FileStream(file, FileMode.Append)); for (int x = 0; x < bitmap.Height; x++) for (int y = 0; y < bitmap.Width; y++) { Color color = bitmap.GetPixel(y, x); writerB.Write(color.R); writerB.Write(color.G); writerB.Write(color.B); } writerB.Close(); } }
Port the provided R code into C++ while preserving the original functionality.
library(pixmap) pixmap::write.pnm write.pnm(theimage, filename)
#include <fstream> int main() { constexpr auto dimx = 800u, dimy = 800u; std::ofstream ofs("first.ppm", ios_base::out | ios_base::binary); ofs << "P6\n" << dimx << ' ' << dimy << "\n255\n"; for (auto j = 0u; j < dimy; ++j) for (auto i = 0u; i < dimx; ++i) ofs << static_cast<char>(i % 256) << static_cast<char>(j % 256) << static_cast<char>((i * j) % 256); }
Write the same code in Java as shown below in R.
library(pixmap) pixmap::write.pnm write.pnm(theimage, filename)
import java.io.BufferedOutputStream; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.nio.charset.StandardCharsets; public class PPMWriter { public void bitmapToPPM(File file, BasicBitmapStorage bitmap) throws IOException { file.delete(); try (var os = new FileOutputStream(file, true); var bw = new BufferedOutputStream(os)) { var header = String.format("P6\n%d %d\n255\n", bitmap.getWidth(), bitmap.getHeight()); bw.write(header.getBytes(StandardCharsets.US_ASCII)); for (var y = 0; y < bitmap.getHeight(); y++) { for (var x = 0; x < bitmap.getWidth(); x++) { var pixel = bitmap.getPixel(x, y); bw.write(pixel.getRed()); bw.write(pixel.getGreen()); bw.write(pixel.getBlue()); } } } } }
Translate the given R code snippet into Python without altering its behavior.
library(pixmap) pixmap::write.pnm write.pnm(theimage, filename)
import io ppmfileout = io.StringIO('') def writeppmp3(self, f): self.writeppm(f, ppmformat='P3') def writeppm(self, f, ppmformat='P6'): assert ppmformat in ['P3', 'P6'], 'Format wrong' magic = ppmformat + '\n' comment = ' maxval = max(max(max(bit) for bit in row) for row in self.map) assert ppmformat == 'P3' or 0 <= maxval < 256, 'R,G,B must fit in a byte' if ppmformat == 'P6': fwrite = lambda s: f.write(bytes(s, 'UTF-8')) maxval = 255 else: fwrite = f.write numsize=len(str(maxval)) fwrite(magic) fwrite(comment) fwrite('%i %i\n%i\n' % (self.width, self.height, maxval)) for h in range(self.height-1, -1, -1): for w in range(self.width): r, g, b = self.get(w, h) if ppmformat == 'P3': fwrite(' %*i %*i %*i' % (numsize, r, numsize, g, numsize, b)) else: fwrite('%c%c%c' % (r, g, b)) if ppmformat == 'P3': fwrite('\n') Bitmap.writeppmp3 = writeppmp3 Bitmap.writeppm = writeppm bitmap = Bitmap(4, 4, black) bitmap.fillrect(1, 0, 1, 2, white) bitmap.set(3, 3, Colour(127, 0, 63)) bitmap.writeppmp3(ppmfileout) print(ppmfileout.getvalue()) ppmfileout = open('tmp.ppm', 'wb') bitmap.writeppm(ppmfileout) ppmfileout.close()
Generate a VB translation of this R snippet without changing its computational steps.
library(pixmap) pixmap::write.pnm write.pnm(theimage, filename)
Public Shared Sub SaveRasterBitmapToPpmFile(ByVal rasterBitmap As RasterBitmap, ByVal filepath As String) Dim header As String = String.Format("P6{0}{1}{2}{3}{0}255{0}", vbLf, rasterBitmap.Width, " "c, rasterBitmap.Height) Dim bufferSize As Integer = header.Length + (rasterBitmap.Width * rasterBitmap.Height * 3) Dim bytes(bufferSize - 1) As Byte Buffer.BlockCopy(Encoding.ASCII.GetBytes(header.ToString), 0, bytes, 0, header.Length) Dim index As Integer = header.Length For y As Integer = 0 To rasterBitmap.Height - 1 For x As Integer = 0 To rasterBitmap.Width - 1 Dim color As Rgb = rasterBitmap.GetPixel(x, y) bytes(index) = color.R bytes(index + 1) = color.G bytes(index + 2) = color.B index += 3 Next Next My.Computer.FileSystem.WriteAllBytes(filepath, bytes, False) End Sub
Transform the following R implementation into Go, maintaining the same output and logic.
library(pixmap) pixmap::write.pnm write.pnm(theimage, filename)
package raster import ( "fmt" "io" "os" ) func (b *Bitmap) WritePpmTo(w io.Writer) (err error) { if _, err = fmt.Fprintln(w, "P6"); err != nil { return } for _, c := range b.Comments { if _, err = fmt.Fprintln(w, c); err != nil { return } } _, err = fmt.Fprintf(w, "%d %d\n255\n", b.cols, b.rows) if err != nil { return } b3 := make([]byte, 3*len(b.px)) n1 := 0 for _, px := range b.px { b3[n1] = px.R b3[n1+1] = px.G b3[n1+2] = px.B n1 += 3 } if _, err = w.Write(b3); err != nil { return } return } func (b *Bitmap) WritePpmFile(fn string) (err error) { var f *os.File if f, err = os.Create(fn); err != nil { return } if err = b.WritePpmTo(f); err != nil { return } return f.Close() }
Can you help me rewrite this code in C instead of Racket, keeping it the same logically?
(define (bitmap->ppm bitmap output-port) (define height (send bitmap get-height)) (define width (send bitmap get-width)) (define buffer (make-bytes (* width height 4))) (send bitmap get-argb-pixels 0 0 width height buffer) (parameterize ([current-output-port output-port]) (printf "P3\n~a ~a\n255" width height) (for ([i (* width height)]) (define pixel-position (* 4 i)) (when (= (modulo i width) 0) (printf "\n")) (printf "~s ~s ~s " (bytes-ref buffer (+ pixel-position 1)) (bytes-ref buffer (+ pixel-position 2)) (bytes-ref buffer (+ pixel-position 3)))))) (call-with-output-file "image.ppm" #:exists 'replace #:mode 'text (lambda (out) (bitmap->ppm bm out))) (define (bitmap->ppm bitmap output-port) (define height (send bitmap get-height)) (define width (send bitmap get-width)) (define buffer (make-bytes (* width height 4))) (send bitmap get-argb-pixels 0 0 width height buffer) (parameterize ([current-output-port output-port]) (printf "P6\n~a ~a\n255\n" width height) (for ([i (* width height)]) (define pixel-position (* 4 i)) (write-byte (bytes-ref buffer (+ pixel-position 1))) (write-byte (bytes-ref buffer (+ pixel-position 2))) (write-byte (bytes-ref buffer (+ pixel-position 3)))))) (call-with-output-file "image.ppm" #:exists 'replace #:mode 'binary (lambda (out) (bitmap->ppm bm out)))
#include <stdlib.h> #include <stdio.h> int main(void) { const int dimx = 800, dimy = 800; int i, j; FILE *fp = fopen("first.ppm", "wb"); (void) fprintf(fp, "P6\n%d %d\n255\n", dimx, dimy); for (j = 0; j < dimy; ++j) { for (i = 0; i < dimx; ++i) { static unsigned char color[3]; color[0] = i % 256; color[1] = j % 256; color[2] = (i * j) % 256; (void) fwrite(color, 1, 3, fp); } } (void) fclose(fp); return EXIT_SUCCESS; }
Port the provided Racket code into C# while preserving the original functionality.
(define (bitmap->ppm bitmap output-port) (define height (send bitmap get-height)) (define width (send bitmap get-width)) (define buffer (make-bytes (* width height 4))) (send bitmap get-argb-pixels 0 0 width height buffer) (parameterize ([current-output-port output-port]) (printf "P3\n~a ~a\n255" width height) (for ([i (* width height)]) (define pixel-position (* 4 i)) (when (= (modulo i width) 0) (printf "\n")) (printf "~s ~s ~s " (bytes-ref buffer (+ pixel-position 1)) (bytes-ref buffer (+ pixel-position 2)) (bytes-ref buffer (+ pixel-position 3)))))) (call-with-output-file "image.ppm" #:exists 'replace #:mode 'text (lambda (out) (bitmap->ppm bm out))) (define (bitmap->ppm bitmap output-port) (define height (send bitmap get-height)) (define width (send bitmap get-width)) (define buffer (make-bytes (* width height 4))) (send bitmap get-argb-pixels 0 0 width height buffer) (parameterize ([current-output-port output-port]) (printf "P6\n~a ~a\n255\n" width height) (for ([i (* width height)]) (define pixel-position (* 4 i)) (write-byte (bytes-ref buffer (+ pixel-position 1))) (write-byte (bytes-ref buffer (+ pixel-position 2))) (write-byte (bytes-ref buffer (+ pixel-position 3)))))) (call-with-output-file "image.ppm" #:exists 'replace #:mode 'binary (lambda (out) (bitmap->ppm bm out)))
using System; using System.IO; class PPMWriter { public static void WriteBitmapToPPM(string file, Bitmap bitmap) { var writer = new StreamWriter(file); writer.WriteLine("P6"); writer.WriteLine($"{bitmap.Width} {bitmap.Height}"); writer.WriteLine("255"); writer.Close(); var writerB = new BinaryWriter(new FileStream(file, FileMode.Append)); for (int x = 0; x < bitmap.Height; x++) for (int y = 0; y < bitmap.Width; y++) { Color color = bitmap.GetPixel(y, x); writerB.Write(color.R); writerB.Write(color.G); writerB.Write(color.B); } writerB.Close(); } }
Port the provided Racket code into C++ while preserving the original functionality.
(define (bitmap->ppm bitmap output-port) (define height (send bitmap get-height)) (define width (send bitmap get-width)) (define buffer (make-bytes (* width height 4))) (send bitmap get-argb-pixels 0 0 width height buffer) (parameterize ([current-output-port output-port]) (printf "P3\n~a ~a\n255" width height) (for ([i (* width height)]) (define pixel-position (* 4 i)) (when (= (modulo i width) 0) (printf "\n")) (printf "~s ~s ~s " (bytes-ref buffer (+ pixel-position 1)) (bytes-ref buffer (+ pixel-position 2)) (bytes-ref buffer (+ pixel-position 3)))))) (call-with-output-file "image.ppm" #:exists 'replace #:mode 'text (lambda (out) (bitmap->ppm bm out))) (define (bitmap->ppm bitmap output-port) (define height (send bitmap get-height)) (define width (send bitmap get-width)) (define buffer (make-bytes (* width height 4))) (send bitmap get-argb-pixels 0 0 width height buffer) (parameterize ([current-output-port output-port]) (printf "P6\n~a ~a\n255\n" width height) (for ([i (* width height)]) (define pixel-position (* 4 i)) (write-byte (bytes-ref buffer (+ pixel-position 1))) (write-byte (bytes-ref buffer (+ pixel-position 2))) (write-byte (bytes-ref buffer (+ pixel-position 3)))))) (call-with-output-file "image.ppm" #:exists 'replace #:mode 'binary (lambda (out) (bitmap->ppm bm out)))
#include <fstream> int main() { constexpr auto dimx = 800u, dimy = 800u; std::ofstream ofs("first.ppm", ios_base::out | ios_base::binary); ofs << "P6\n" << dimx << ' ' << dimy << "\n255\n"; for (auto j = 0u; j < dimy; ++j) for (auto i = 0u; i < dimx; ++i) ofs << static_cast<char>(i % 256) << static_cast<char>(j % 256) << static_cast<char>((i * j) % 256); }
Please provide an equivalent version of this Racket code in Java.
(define (bitmap->ppm bitmap output-port) (define height (send bitmap get-height)) (define width (send bitmap get-width)) (define buffer (make-bytes (* width height 4))) (send bitmap get-argb-pixels 0 0 width height buffer) (parameterize ([current-output-port output-port]) (printf "P3\n~a ~a\n255" width height) (for ([i (* width height)]) (define pixel-position (* 4 i)) (when (= (modulo i width) 0) (printf "\n")) (printf "~s ~s ~s " (bytes-ref buffer (+ pixel-position 1)) (bytes-ref buffer (+ pixel-position 2)) (bytes-ref buffer (+ pixel-position 3)))))) (call-with-output-file "image.ppm" #:exists 'replace #:mode 'text (lambda (out) (bitmap->ppm bm out))) (define (bitmap->ppm bitmap output-port) (define height (send bitmap get-height)) (define width (send bitmap get-width)) (define buffer (make-bytes (* width height 4))) (send bitmap get-argb-pixels 0 0 width height buffer) (parameterize ([current-output-port output-port]) (printf "P6\n~a ~a\n255\n" width height) (for ([i (* width height)]) (define pixel-position (* 4 i)) (write-byte (bytes-ref buffer (+ pixel-position 1))) (write-byte (bytes-ref buffer (+ pixel-position 2))) (write-byte (bytes-ref buffer (+ pixel-position 3)))))) (call-with-output-file "image.ppm" #:exists 'replace #:mode 'binary (lambda (out) (bitmap->ppm bm out)))
import java.io.BufferedOutputStream; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.nio.charset.StandardCharsets; public class PPMWriter { public void bitmapToPPM(File file, BasicBitmapStorage bitmap) throws IOException { file.delete(); try (var os = new FileOutputStream(file, true); var bw = new BufferedOutputStream(os)) { var header = String.format("P6\n%d %d\n255\n", bitmap.getWidth(), bitmap.getHeight()); bw.write(header.getBytes(StandardCharsets.US_ASCII)); for (var y = 0; y < bitmap.getHeight(); y++) { for (var x = 0; x < bitmap.getWidth(); x++) { var pixel = bitmap.getPixel(x, y); bw.write(pixel.getRed()); bw.write(pixel.getGreen()); bw.write(pixel.getBlue()); } } } } }
Rewrite the snippet below in Python so it works the same as the original Racket code.
(define (bitmap->ppm bitmap output-port) (define height (send bitmap get-height)) (define width (send bitmap get-width)) (define buffer (make-bytes (* width height 4))) (send bitmap get-argb-pixels 0 0 width height buffer) (parameterize ([current-output-port output-port]) (printf "P3\n~a ~a\n255" width height) (for ([i (* width height)]) (define pixel-position (* 4 i)) (when (= (modulo i width) 0) (printf "\n")) (printf "~s ~s ~s " (bytes-ref buffer (+ pixel-position 1)) (bytes-ref buffer (+ pixel-position 2)) (bytes-ref buffer (+ pixel-position 3)))))) (call-with-output-file "image.ppm" #:exists 'replace #:mode 'text (lambda (out) (bitmap->ppm bm out))) (define (bitmap->ppm bitmap output-port) (define height (send bitmap get-height)) (define width (send bitmap get-width)) (define buffer (make-bytes (* width height 4))) (send bitmap get-argb-pixels 0 0 width height buffer) (parameterize ([current-output-port output-port]) (printf "P6\n~a ~a\n255\n" width height) (for ([i (* width height)]) (define pixel-position (* 4 i)) (write-byte (bytes-ref buffer (+ pixel-position 1))) (write-byte (bytes-ref buffer (+ pixel-position 2))) (write-byte (bytes-ref buffer (+ pixel-position 3)))))) (call-with-output-file "image.ppm" #:exists 'replace #:mode 'binary (lambda (out) (bitmap->ppm bm out)))
import io ppmfileout = io.StringIO('') def writeppmp3(self, f): self.writeppm(f, ppmformat='P3') def writeppm(self, f, ppmformat='P6'): assert ppmformat in ['P3', 'P6'], 'Format wrong' magic = ppmformat + '\n' comment = ' maxval = max(max(max(bit) for bit in row) for row in self.map) assert ppmformat == 'P3' or 0 <= maxval < 256, 'R,G,B must fit in a byte' if ppmformat == 'P6': fwrite = lambda s: f.write(bytes(s, 'UTF-8')) maxval = 255 else: fwrite = f.write numsize=len(str(maxval)) fwrite(magic) fwrite(comment) fwrite('%i %i\n%i\n' % (self.width, self.height, maxval)) for h in range(self.height-1, -1, -1): for w in range(self.width): r, g, b = self.get(w, h) if ppmformat == 'P3': fwrite(' %*i %*i %*i' % (numsize, r, numsize, g, numsize, b)) else: fwrite('%c%c%c' % (r, g, b)) if ppmformat == 'P3': fwrite('\n') Bitmap.writeppmp3 = writeppmp3 Bitmap.writeppm = writeppm bitmap = Bitmap(4, 4, black) bitmap.fillrect(1, 0, 1, 2, white) bitmap.set(3, 3, Colour(127, 0, 63)) bitmap.writeppmp3(ppmfileout) print(ppmfileout.getvalue()) ppmfileout = open('tmp.ppm', 'wb') bitmap.writeppm(ppmfileout) ppmfileout.close()
Preserve the algorithm and functionality while converting the code from Racket to VB.
(define (bitmap->ppm bitmap output-port) (define height (send bitmap get-height)) (define width (send bitmap get-width)) (define buffer (make-bytes (* width height 4))) (send bitmap get-argb-pixels 0 0 width height buffer) (parameterize ([current-output-port output-port]) (printf "P3\n~a ~a\n255" width height) (for ([i (* width height)]) (define pixel-position (* 4 i)) (when (= (modulo i width) 0) (printf "\n")) (printf "~s ~s ~s " (bytes-ref buffer (+ pixel-position 1)) (bytes-ref buffer (+ pixel-position 2)) (bytes-ref buffer (+ pixel-position 3)))))) (call-with-output-file "image.ppm" #:exists 'replace #:mode 'text (lambda (out) (bitmap->ppm bm out))) (define (bitmap->ppm bitmap output-port) (define height (send bitmap get-height)) (define width (send bitmap get-width)) (define buffer (make-bytes (* width height 4))) (send bitmap get-argb-pixels 0 0 width height buffer) (parameterize ([current-output-port output-port]) (printf "P6\n~a ~a\n255\n" width height) (for ([i (* width height)]) (define pixel-position (* 4 i)) (write-byte (bytes-ref buffer (+ pixel-position 1))) (write-byte (bytes-ref buffer (+ pixel-position 2))) (write-byte (bytes-ref buffer (+ pixel-position 3)))))) (call-with-output-file "image.ppm" #:exists 'replace #:mode 'binary (lambda (out) (bitmap->ppm bm out)))
Public Shared Sub SaveRasterBitmapToPpmFile(ByVal rasterBitmap As RasterBitmap, ByVal filepath As String) Dim header As String = String.Format("P6{0}{1}{2}{3}{0}255{0}", vbLf, rasterBitmap.Width, " "c, rasterBitmap.Height) Dim bufferSize As Integer = header.Length + (rasterBitmap.Width * rasterBitmap.Height * 3) Dim bytes(bufferSize - 1) As Byte Buffer.BlockCopy(Encoding.ASCII.GetBytes(header.ToString), 0, bytes, 0, header.Length) Dim index As Integer = header.Length For y As Integer = 0 To rasterBitmap.Height - 1 For x As Integer = 0 To rasterBitmap.Width - 1 Dim color As Rgb = rasterBitmap.GetPixel(x, y) bytes(index) = color.R bytes(index + 1) = color.G bytes(index + 2) = color.B index += 3 Next Next My.Computer.FileSystem.WriteAllBytes(filepath, bytes, False) End Sub
Write the same code in Go as shown below in Racket.
(define (bitmap->ppm bitmap output-port) (define height (send bitmap get-height)) (define width (send bitmap get-width)) (define buffer (make-bytes (* width height 4))) (send bitmap get-argb-pixels 0 0 width height buffer) (parameterize ([current-output-port output-port]) (printf "P3\n~a ~a\n255" width height) (for ([i (* width height)]) (define pixel-position (* 4 i)) (when (= (modulo i width) 0) (printf "\n")) (printf "~s ~s ~s " (bytes-ref buffer (+ pixel-position 1)) (bytes-ref buffer (+ pixel-position 2)) (bytes-ref buffer (+ pixel-position 3)))))) (call-with-output-file "image.ppm" #:exists 'replace #:mode 'text (lambda (out) (bitmap->ppm bm out))) (define (bitmap->ppm bitmap output-port) (define height (send bitmap get-height)) (define width (send bitmap get-width)) (define buffer (make-bytes (* width height 4))) (send bitmap get-argb-pixels 0 0 width height buffer) (parameterize ([current-output-port output-port]) (printf "P6\n~a ~a\n255\n" width height) (for ([i (* width height)]) (define pixel-position (* 4 i)) (write-byte (bytes-ref buffer (+ pixel-position 1))) (write-byte (bytes-ref buffer (+ pixel-position 2))) (write-byte (bytes-ref buffer (+ pixel-position 3)))))) (call-with-output-file "image.ppm" #:exists 'replace #:mode 'binary (lambda (out) (bitmap->ppm bm out)))
package raster import ( "fmt" "io" "os" ) func (b *Bitmap) WritePpmTo(w io.Writer) (err error) { if _, err = fmt.Fprintln(w, "P6"); err != nil { return } for _, c := range b.Comments { if _, err = fmt.Fprintln(w, c); err != nil { return } } _, err = fmt.Fprintf(w, "%d %d\n255\n", b.cols, b.rows) if err != nil { return } b3 := make([]byte, 3*len(b.px)) n1 := 0 for _, px := range b.px { b3[n1] = px.R b3[n1+1] = px.G b3[n1+2] = px.B n1 += 3 } if _, err = w.Write(b3); err != nil { return } return } func (b *Bitmap) WritePpmFile(fn string) (err error) { var f *os.File if f, err = os.Create(fn); err != nil { return } if err = b.WritePpmTo(f); err != nil { return } return f.Close() }