我正在尝试将以下 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 附加到 byte
、img.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/