Last active
September 22, 2015 18:13
-
-
Save k3kaimu/c99d3e38199b7094b357 to your computer and use it in GitHub Desktop.
png画像にバイナリデータを埋め込んだり、pngに埋め込まれたバイナリデータを抽出するヤツ
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import imageformats; | |
import std.algorithm; | |
import std.conv; | |
import std.exception; | |
import std.file; | |
import std.math; | |
import std.stdio; | |
import std.string; | |
void main() | |
{ | |
ubyte[] dst = cast(ubyte[])`×ご検証 | |
○ご健勝 | |
`; | |
encodeBng(dst, "output.png", 100); | |
decodeBng("output.png", dst); | |
std.file.write("output2.dat", dst); | |
} | |
void decodeBng(string pngFile, ref ubyte[] dst) | |
{ | |
auto img = read_png(pngFile, 4); | |
enforce(img.c == ColFmt.RGBA); | |
auto ps = img.pixels; | |
immutable uint numBytes = (cast(uint[])(ps[0 .. 4].reverse(), ps))[0]; | |
dst.length = numBytes; | |
dst[] = ps[4 .. 4 + numBytes]; | |
} | |
void encodeBng(in ubyte[] data, string pngFile, size_t minWH = 0) | |
{ | |
immutable numPixels = (data.length + 4) / 4; | |
size_t w = cast(size_t)sqrt(cast(real)numPixels); | |
size_t h = numPixels / w; | |
if(numPixels > w * h) ++w; | |
if(w < minWH) w = minWH; | |
if(h < minWH) h = minWH; | |
auto buf = new ubyte[w * h * 4]; | |
buf[0 .. 4] = (a => (a.reverse(), a))(cast(ubyte[])([data.length].dup))[]; | |
buf[4 .. 4 + data.length] = data[]; | |
write_png(pngFile, w, h, buf, 4); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment