fortran66のブログ

fortran について書きます。

【メモ帳】Julia 言語で BMP write

Julia 言語よく分からんw

型変換規則がよく分からない。構造体をまとめて書きだす方法も分からない。構造体に初期値を与えられるのかも分からない。ASCII 文字型も分からない。

頭部に定義部が無いと軽い感じになるのだなと思いました。xxx...end の block 構造が重いわけではないのかと。

struct Bmp_file_header
    bfType::AbstractString # 'BM'  B=42 M=4d 
    bfSize::Int32 # file size in bytes
    bfReserved1::Int16
    bfReserved2::Int16
    bfOffBits::Int32
end

struct Bmp_info_header
    biSize::Int32          # = Z'28' ! size of bmp_info_header ; 40bytes 
    biWidth::Int32
    biHeight::Int32
    biPlanes::Int16        # = 1 ! always 1
    biBitCount::Int16
    biCompression::Int32   # = 0 ! 0:nocompression, 1:8bitRLE, 2:4bitRLE, 3:bitfield
    biSizeImage::Int32
    biXPelsPerMeter::Int32 # = 3780 ! 96dpi
    biYPelsPerMeter::Int32 # = 3780 ! 96dpi 
    biClrUsed::Int32       # = 0
    biClrImportant::Int32  # = 0 
end

struct Rgb
    ib::UInt8
    ig::UInt8
    ir::UInt8
end

function wr_bmp(bmp, fn)
    ny, nx = size(bmp)
    Array{Rgb}(undef, ny, nx)
    bmp_file_header = Bmp_file_header("BM", 14 + 40 + 0 + (3 * nx + mod(ny, 4)) * ny, 0, 0, 14 + 40) 
    bmp_info_header = Bmp_info_header(0x28, nx, ny, 1, 24, 0, (3 * nx + mod(ny, 4)) * ny, 3780, 3780, 0, 0)
    open(fn * ".bmp", "w") do file
        write(file, bmp_file_header.bfType)
        write(file, bmp_file_header.bfSize)
        write(file, bmp_file_header.bfReserved1)
        write(file, bmp_file_header.bfReserved2)
        write(file, bmp_file_header.bfOffBits)
        
        write(file, bmp_info_header.biSize)
        write(file, bmp_info_header.biWidth)
        write(file, bmp_info_header.biHeight)
        write(file, bmp_info_header.biPlanes)
        write(file, bmp_info_header.biBitCount)
        write(file, bmp_info_header.biCompression)
        write(file, bmp_info_header.biSizeImage)
        write(file, bmp_info_header.biXPelsPerMeter)
        write(file, bmp_info_header.biYPelsPerMeter)
        write(file, bmp_info_header.biClrUsed)
        write(file, bmp_info_header.biClrImportant)
        
        for iy = ny:-1:1
            for ix = 1:nx
                write(file, bmp[iy, ix].ib, bmp[iy, ix].ig, bmp[iy, ix].ir)
            end
            for ix =1:nx % 4
                write(file, convert(UInt8, 0))
            end    
        end    
    end    
end
nx = 250; ny = 250
B = Array{Rgb}(undef, ny, nx)
for ix = 1:nx
    for iy = 1:ny
        B[ix, iy] = Rgb(convert(UInt8, 0), convert(UInt8, 0), convert(UInt8, 255))
    end
end

wr_bmp(B, "test")

f:id:fortran66:20190816002555p:plain
bmp -> png 手動変換

Julia 1.0 Programming Complete Reference Guide: Discover Julia, a high-performance language for technical computing

Julia 1.0 Programming Complete Reference Guide: Discover Julia, a high-performance language for technical computing