對於學校,我們必須在速記中做一個項目,我選擇了使用bmp並將文本放入其中。它對正常的圖片效果很好,但是從具有相同字節序列的圖片開始,例如白色區域或出現問題的圖像是this picture。將圖像轉換爲字節數組的問題
當我從字節陣列中的文字在圖像中製作,然後我讀回字節陣列已經改變。而我所做的唯一的事情是從字節陣列和圖像中創建一個圖像回一個字節陣列。
這是我的代碼:
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;
}
}
可能很難在具有如此純色的圖像中隱藏信息。 – sarnold 2011-03-24 09:07:55
什麼樣的錯誤?這是一個例外嗎?它什麼都沒有? – Arthur 2011-03-24 09:08:54
將隨機字節轉換爲UTF通常會導致損壞。你永遠不會從該字符串中檢索正確的字節。 – CodingBarfield 2011-03-24 11:05:48