将Image Python代码转换为C#

时间:2014-02-06 23:46:58

标签: c# python image

我正在尝试将以下Python代码移植到C#。

import Image, base64, StringIO
def pngstore(input):
    input = open(input, "r").read()
    pixels = len(input) / 3

    img = Image.new("RGB", (pixels, 1), (0,0,0))

    bytes = []
    for character in input:
        bytes.append(ord(character))

    while len(bytes) % 3 > 0:
        bytes.append(0)

    for x in range(0, pixels):
        img.putpixel((x, 0), (bytes[x*3], bytes[x*3 + 1], bytes[x*3 + 2]))

    output = StringIO.StringIO()
    img.save(output, format="PNG")
    output.seek(0)

    return base64.b64encode(output.read())

while()循环,其中byteimg.putpixel附加0,而ord(character))的追加是我有点困惑的地方。

FileInfo file = new FileInfo(FD.FileName);
long pixels = file.Length / 3;
byte[] bytes = File.ReadAllBytes(file.FullName);

Bitmap image = new Bitmap(Image.FromFile(fileToOpen));
while (bytes.Length % 3 > 0)
{
    bytes.CopyTo(?); // ?
}

foreach (var x in Enumerable.Range(0, (int)pixels))
{
    //Color color = Color.FromArgb(, 0, 0, 0);
    //image.SetPixel(x, 0, color);
}

image.Save("newfile.png", ImageFormat.Png);

2 个答案:

答案 0 :(得分:1)

这不是你想要的答案,但你有没有看过IronPython?编译后的Python(MSIL)可以与已编译的C#(仍然是MSIL)完美地一起运行。因此,您不必从Python移植到C#,仍然可以提供与普通客户无法区分的程序集。

这不是你的问题,但它是一种如何通过不移植来完成工作的方法。显然,可能仍有更深层次的理由倾向于移植。

答案 1 :(得分:1)

bytes.append(ord(character))的for循环将字符从输入转换为数值。 C#通过File.ReadAllBytes()立即将字节作为数值读取。

while循环确保bytes的长度可被3整除。它以零填充列表。 Array.Resize()可能是要走的路。我认为这是padding an existing array in C#的最佳解决方案。我认为File.ReadAllBytes()不能强制添加填充也不能填充现有数组。

整个图像只是一行像素。带img.putpixel()的循环从左到右遍历图像,并将当前像素的颜色设置为颜色,RGB通道设置为相应字节的值。不使用Alpha通道。使用Color.FromArgb() with three parameters就足够了。

要修复的其他细节:您想要初始化new, empty Bitmap with given dimensions。无论如何,new Bitmap(Image.FromFile(fileToOpen))可以简化为new Bitmap(fileToOpen)

最终代码(没有Base64编码,因为你似乎不想要它)是

FileInfo file = new FileInfo(FD.FileName);
int pixels = (int)file.Length / 3; // int must be enough (anyway limited by interfaces accepting only int)

byte[] bytes = File.ReadAllBytes(file.FullName);
if (file.Length % 3 != 0) {
    Array.Resize(ref bytes, 3 * pixels + 3);
}

Bitmap image = new Bitmap(pixels, 1);
foreach (var x in Enumerable.Range(0, pixels)) {
    image.SetPixel(x, 0, Color.FromArgb(bytes[3*x] , bytes[3*x+1], bytes[3*x+2]));
}
image.Save("newfile.png", ImageFormat.Png);