【问题标题】:Converting Image Python code to C#将图像 Python 代码转换为 C#
【发布时间】:2014-03-04 04:51:41
【问题描述】:

我正在尝试将以下 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() 循环将 0 附加到 byteimg.putpixelord(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);

【问题讨论】:

    标签: c# python image


    【解决方案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 dimensionsnew 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);
    

    【讨论】:

      【解决方案2】:

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

      这不能回答您的问题,但它是一种通过完全不移植来完成工作的方法。显然,可能还有更深刻的理由更喜欢移植。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2017-09-23
        • 2011-06-06
        • 2018-09-22
        • 2016-04-19
        • 2020-03-03
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多