c# - 将图像 Python 代码转换为 C#

标签 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() 循环将 0 附加到 byteimg.putpixel 以及附加 ord(字符)) 是我有点困惑的地方。

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);

最佳答案

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

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

整个图像只是一行像素。 img.putpixel() 循环从左到右遍历图像,并将当前像素的颜色设置为 RGB channel 设置为相应字节值的颜色。不使用 Alpha channel 。使用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);

关于c# - 将图像 Python 代码转换为 C#,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21616528/

相关文章:

c# - 如何有效地对HttpWebRequests进行多线程处理?

python - 将 lambda 应用于数据框,但仅限于特定的行数

Python Pandas : float values break down when df. 列 = df.columns.droplevel()

python - 如何在网络风格的 Plotly 图中设置单独的线宽(Python 3.6 | plot.ly)?

R:对数尺度的图像强度

c# - 从 web 用户控件调用父 aspx 页面的函数

c# - 在程序运行之间保持变量值

php - 使用php mysql动态显示图像

c# - ASP.NET Web API - 尝试传递参数时不支持 GET HTTP 动词 (405)

image - 如何从小部件在 Flutter 中创建 A4 或 PDF 中的图像?