无法从复制的像素创建新的位图

Can't create a new bitmap from copied pixels

我有一张图片,我想在其中存储一条消息(通过更改所需每个像素的最后一个有效位)。我正在使用位图将像素加载到列表中。

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }

    private string oEcrypt;
    private string oDecrypt;
    private List<ARGB> toCipherList = new List<ARGB>();
    private int Width;
    private int Height;
    private void button1_Click(object sender, EventArgs e)
    {
        // here i'm editing toCipherList
        Bitmap img = new Bitmap(Width, Height);
        for (int i = 0; i < img.Width; i++)
        {
            for (int j = 0; j < img.Height; j++)
            {
                Color pixel = Color.FromArgb(toCipherList[i].A, toCipherList[i].R, toCipherList[i].G, toCipherList[i].B);
                img.SetPixel(i, j, pixel);
            }
        }
        img.Save("output.jpg");
    }

    private void button3_Click(object sender, EventArgs e)
    {
        openFileDialog1.ShowDialog();
        oEcrypt = openFileDialog1.FileName;
        textBox3.Text = oEcrypt;
        Bitmap img = new Bitmap(oEcrypt);
        Width = img.Width;
        Height = img.Height;
        for (int i = 0; i < img.Width; i++)
        {
            for (int j = 0; j < img.Height; j++)
            {
                Color pixel = img.GetPixel(i, j);
                byte A = pixel.A;
                byte R = pixel.R;
                byte G = pixel.G;
                byte B = pixel.B;
                ARGB rGB = new ARGB(A, R, G, B);
                toCipherList.Add(rGB);
            }
        }
    }
    public class ARGB
    {
         public byte A { get; set; }
         public byte R { get; set; }
         public byte G { get; set; }
         public byte B { get; set; }

    public ARGB(byte a, byte r, byte g, byte b)
    {
        this.A = a;
        this.R = r;
        this.G = g;
        this.B = b;
    }
}

问题是,即使我不更改像素,只是用我从原始图像获得的像素制作一个新的位图,我得到的输出图像带有一些随机的垂直线。我检查了存储在列表中的值,它们与加载时的原始图像相同。我需要复制更多信息吗? 我正在尝试 中的 GetCopyOf 方法,但它对我不起作用,或者我做错了什么。

这里有很多很多更好的方法。但是,您的问题出在列表上。简而言之,您没有阅读每个元素。试试这个

var index = 0;
...

// loops here
Color pixel = Color.FromArgb(toCipherList[index].A, toCipherList[index].R, toCipherList[index].G, toCipherList[index].B);
index++;

一些提示,

  1. 更快地使用 LockBits
  2. 使用 32bpp 然后你的像素可以存储为整数
  3. 不要理会你的 ARGB 类 见上文