对于学校我们必须做一个速记项目,我选择使用bmp并将文本放入其中。它可以正常使用普通图片,但是当您拥有相同字节序列的图片时,例如白色区域或我遇到问题的图像是this picture。
当我从bytearray中创建文本在图像中并且我将其读回时,bytearray已经改变。而我唯一做的就是从bytearray和图像中生成一个像素阵列。
这是我的代码:
namespace steganografie
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void btnFile_Click(object sender, EventArgs e)
{
OpenFileDialog dialog = new OpenFileDialog();
dialog.Filter = "bmp files (*.bmp)|*.bmp|All files (*.*)|*.*";
dialog.Title = "Select a image";
dialog.InitialDirectory = Application.ExecutablePath;
if (dialog.ShowDialog() == DialogResult.OK)
{
txtText.Enabled = true;
txtFile.Text = dialog.FileName;
byte[] arImage = imageToByteArray(Image.FromFile(txtFile.Text));
txtText.MaxLength = ((arImage.Length -54) /8)-5;
lblCharLeft.Text = txtText.MaxLength+"";
lblCharLeft.Tag = txtText.MaxLength;
picOriginal.Image = Image.FromFile(dialog.FileName);
}
}
private void btnSteganografie_Click(object sender, EventArgs e)
{
byte[] arImage = imageToByteArray(Image.FromFile(txtFile.Text));
string input = txtText.Text;
string inputInBits = GetBits(input);
char[] bits = inputInBits.ToCharArray();
int i = 0;
for (i = 54; (i < arImage.Length & i < bits.Length+54); i++)
{
if ((int)arImage[i] == 0)
{
arImage[i] = (byte)2;
}
if ((int)arImage[i] == 255)
{
byte bBit = new byte();
bBit = 2;
arImage[i] = (byte)(arImage[i]-bBit);
}
int lastBit = ((int)arImage[i]) % 2;
int dataBit = ((int)bits[i - 54])%2;
if (lastBit != dataBit)
{
arImage[i]++;
}
}
arImage[i] = 0;
Image result = byteArrayToImage(arImage);
picEncoded.Image = result;
SaveFileDialog sfd = new SaveFileDialog();
if (sfd.ShowDialog() == DialogResult.OK)
{
result.Save(sfd.FileName+".bmp",System.Drawing.Imaging.ImageFormat.Bmp);
}
}
public string GetBits(string input)
{
StringBuilder sbBuilder = new StringBuilder();
byte[] bytes = Encoding.Unicode.GetBytes(input);
foreach (byte bByte in Encoding.Unicode.GetBytes(input))
{
int iByte = (int)bByte;
for (int i = 7; i >= 0 & (iByte!=0 | i!=7); i--)
{
if (iByte - Math.Pow(2, i) >= 0)
{
sbBuilder.Append("1");
iByte -= (int)Math.Pow(2, i);
}
else
{
sbBuilder.Append("0");
}
}
}
return sbBuilder.ToString();
}
public byte[] imageToByteArray(System.Drawing.Image imageIn)
{
MemoryStream ms = new MemoryStream();
imageIn.Save(ms, System.Drawing.Imaging.ImageFormat.Bmp);
return ms.ToArray();
}
public Image byteArrayToImage(byte[] byteArrayIn)
{
//**********ERROR HAPPENS HERE *************
MemoryStream ms = new MemoryStream(byteArrayIn);
Image returnImage = Image.FromStream(ms);
byte[] arImageTEST = imageToByteArray(returnImage);
//**********byteArrayIn should be the same as arImageTEST ***********
return returnImage;
}
}
答案 0 :(得分:0)
可能与此信息有关[{3}}:
你必须保持流开放 图像的生命周期。
希望它有所帮助。