3 / 3 / 1
Регистрация: 05.08.2011
Сообщений: 102
1
.NET 3.x

Как сохранить файл jpg не меняя его физический размер?

07.12.2011, 13:16. Показов 1526. Ответов 1
Метки нет (Все метки)

Author24 — интернет-сервис помощи студентам
Здравствуйте. Пишу программу для стеганографии изображений. На входе есть 2 графических файла формат jpg размером 35,0 Кб оригинальное и модифицированное изображение формата jpg отрываю их с помощью программы они оба загружаются нормально сохраняю модифицированное изображение в формат .jpg и файл теперь весит 34,9 Кб т.е. размер файла меняется уменьшается куда девается 1 байт никак не пойму может дело в качестве изображения. Как сохранить модифицированное изображение файл формата .jpg не меняя его физического размера и не теряя качества изображения?

C#
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
public partial class Steganography : Form
    {
        PasswordForm passwordForm = new PasswordForm();
        Bitmap bmpOriginal;
        Bitmap bmpModified;
        byte[] exampleFile;
        byte[] exFile;
        byte[] file;
 
        public Steganography()
        {
            InitializeComponent();
        }
 
        private void SteganographyAlgorithmForm_Paint(object sender, PaintEventArgs e)
        {
            OriginalPictureBox.Image = bmpOriginal;
            if (bmpModified == null)
            {
                return;
            }
 
            ModifiedPictureBox.Image = bmpModified;
        }
 
        private byte[] PasswordSHA(string password)
        {
            return new SHA256Managed().ComputeHash(Encoding.ASCII.GetBytes(password));
        }
 
        private byte[] EncryptionSymmetricAlgorithm(byte[] file, byte[] password, SymmetricAlgorithm sa, CipherMode cm, PaddingMode pm)
        {
            byte[] buffer;
            byte[] cipherbytes;
 
            sa.Key = password;
            sa.IV = new byte[] { 2, 3, 1, 86, 31, 76, 24, 46, 31, 76, 24, 46, 86, 31, 76, 24 };
 
            sa.Mode = cm;
            sa.Padding = pm;
 
            MemoryStream ms = new MemoryStream();
            CryptoStream cs = new CryptoStream(
                ms,
                sa.CreateEncryptor(),
                CryptoStreamMode.Write);
 
            buffer = file;
            cs.Write(buffer, 0, buffer.Length);
            cs.Close();
 
            cipherbytes = ms.ToArray();
            ms.Close();
            return cipherbytes;
        }
 
        private void SaveAImage(byte[] file)
        {
            try
            {
                this.Cursor = Cursors.WaitCursor;
 
                bmpModified = new Bitmap(bmpOriginal, bmpOriginal.Width, bmpOriginal.Height);
 
                int numberbytes = file.Length;
                byte[] bytesOriginal = new byte[numberbytes + 1];
                bytesOriginal[0] = (byte)numberbytes;
 
                for (int i = 0; i < file.Length; i++)
                {
                    bytesOriginal[i + 1] = file[i];
                }
 
                int byteCount = 0;
 
                for (int i = 0; i < bmpOriginal.Width; i++)
                {
                    for (int j = 0; j < bmpOriginal.Height; j++)
                    {
                        if (bytesOriginal.Length == byteCount)
                            return;
 
                        Color clrPixelOriginal = bmpOriginal.GetPixel(i, j);
                        byte r = (byte)((clrPixelOriginal.R & ~0x7) | (bytesOriginal[byteCount] >> 0) & 0x7);
                        byte g = (byte)((clrPixelOriginal.G & ~0x7) | (bytesOriginal[byteCount] >> 3) & 0x7);
                        byte b = (byte)((clrPixelOriginal.B & ~0x3) | (bytesOriginal[byteCount] >> 6) & 0x3);
                        byteCount++;
 
                        bmpModified.SetPixel(i, j, Color.FromArgb(r, g, b));
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("Error hiding message." + ex.Message);
            }
            finally
            {
                this.Cursor = Cursors.Arrow;
 
                Invalidate();
            }
        }
 
        private void ExtractTheFile()
        {
            byte[] bytesExtracted = new byte[256 + 1];
            try
            {
                this.Cursor = Cursors.WaitCursor;
 
                int byteCount = 0;
 
                for (int i = 0; i < bmpModified.Width; i++)
                {
                    for (int j = 0; j < bmpModified.Height; j++)
                    {
                        if (bytesExtracted.Length == byteCount)
                        {
                            return;
                        }
 
                        Color clrPixelModified = bmpModified.GetPixel(i, j);
                        byte bits123 = (byte)((clrPixelModified.R & 0x7) << 0);
                        byte bits456 = (byte)((clrPixelModified.G & 0x7) << 3);
                        byte bits78 = (byte)((clrPixelModified.B & 0x3) << 6);
 
                        bytesExtracted[byteCount] = (byte)(bits78 | bits456 | bits123);
                        byteCount++;
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("Error extracting message." + ex.Message);
            }
            finally
            {
                this.Cursor = Cursors.Arrow;
 
                int numberbytes = bytesExtracted[0];
 
                byte[] file = new byte[numberbytes];
                for (int i = 0; i < numberbytes; i++)
                {
                    file[i] = bytesExtracted[i + 1];
                }
                exFile = file;
            }
        }
 
        private byte[] DecryptionSymmetricAlgorithm(byte[] cipherbytes, byte[] password, SymmetricAlgorithm sa, CipherMode cm, PaddingMode pm)
        {
            byte[] buffer;
 
            sa.Key = password;
            sa.IV = new byte[] { 2, 3, 1, 86, 31, 76, 24, 46, 31, 76, 24, 46, 86, 31, 76, 24 };
 
            sa.Mode = cm;
            sa.Padding = pm;
 
            MemoryStream ms = new MemoryStream(cipherbytes);
            CryptoStream cs = new CryptoStream(
                ms,
                sa.CreateDecryptor(),
                CryptoStreamMode.Read);
 
            buffer = new Byte[cipherbytes.Length];
            cs.Read(buffer, 0, cipherbytes.Length);
            cs.Close();
            ms.Close();
 
            return buffer;
        }
 
        private void openFileToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (openFileDialog.ShowDialog() == DialogResult.OK)
                exampleFile = File.ReadAllBytes(openFileDialog.FileName);
        }
 
        private void originalImageToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (openFileDialog.ShowDialog() == DialogResult.OK)
            {
                bmpOriginal = (Bitmap)Bitmap.FromFile(openFileDialog.FileName);
            }
        }
 
        private void modifiedImageToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (openFileDialog.ShowDialog() == DialogResult.OK)
            {
                bmpOriginal = (Bitmap)Bitmap.FromFile(openFileDialog.FileName);
                bmpModified = (Bitmap)Bitmap.FromFile(openFileDialog.FileName);
            }
        }
 
        private void saveFileToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (passwordForm.ShowDialog() == DialogResult.Cancel)
            {
                return;
            }
 
            ExtractTheFile();
 
            try
            {
                file = DecryptionSymmetricAlgorithm(
                   exFile,
                   PasswordSHA(passwordForm.Password),
                   Rijndael.Create(),
                   CipherMode.ECB,
                   PaddingMode.Zeros
                   );
 
                if (saveFileDialog.ShowDialog() == DialogResult.OK)
                {
                    File.WriteAllText(saveFileDialog.FileName, Encoding.GetEncoding(1251).GetString(file));
                }
 
                
            }
            catch (Exception ex)
            {
                MessageBox.Show("Wrong password. " + ex);
            }
        }
 
        private void modifiedIToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (passwordForm.ShowDialog() == DialogResult.Cancel)
            {
                return;
            }
 
            SaveAImage(EncryptionSymmetricAlgorithm(
                exampleFile,
                PasswordSHA(passwordForm.Password),
                Rijndael.Create(),
                CipherMode.ECB,
                PaddingMode.Zeros
                ));
 
            saveFileDialog.Filter = "jpg files (*.jpg)|*.jpg|All files (*.*)|*.*";
 
            if (saveFileDialog.ShowDialog() == DialogResult.OK)
            {
                long quality = 90L;
 
                if (quality < 0 || quality > 100)
                {
                    throw new ArgumentOutOfRangeException("quality must be between 0 and 100");
                }
 
                EncoderParameter qualityParam = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, quality);
 
                EncoderParameters encoderParameters = new EncoderParameters(1);
                encoderParameters.Param[0] = qualityParam;
                ModifiedPictureBox.Image.Save(saveFileDialog.FileName, GetEncoder(ImageFormat.Jpeg), encoderParameters);
            }
        }
 
        private void exitToolStripMenuItem_Click(object sender, EventArgs e)
        {
            this.Close();
        }
 
        public static ImageCodecInfo GetEncoder(ImageFormat format)
        {
           ImageCodecInfo[] codecs = ImageCodecInfo.GetImageDecoders();
 
           foreach (ImageCodecInfo codec in codecs)
           {
               if (codec.FormatID == format.Guid)
               {
                   return codec;
               }
           }
 
           return null;
       }
 
   public partial class PasswordForm : Form
    {
         public string Password { get; set; }
 
        public PasswordForm()
        {
            InitializeComponent();
        }
 
        private void OKButton_Click(object sender, EventArgs e)
        {
            Password = PasswordTextBox.Text;
            Close();
        }
 
        private void CancelButton_Click(object sender, EventArgs e)
        {
            Password = "";
            Close();
        }
    }
0
Programming
Эксперт
94731 / 64177 / 26122
Регистрация: 12.04.2006
Сообщений: 116,782
07.12.2011, 13:16
Ответы с готовыми решениями:

Как правильно сохранить jpg файл из потока
Здравствуйте подскажите пожалуйста как правильно сохранить jpg из потока ( он скачивается по ссылке...

Как записать текст в файл, не меняя его содержимого?
Здравствуйте. Как записать текст В файл, не меняя его содержимого? У меня есть функция,...

Как сохранить рисунок из Word'a в отдельный файл (*.bmp; *.jpg; *.gif ...)
Конечно, есть вариант сохранить страницу как html и просматривать папку .files. Но мне этот путь не...

Как сохранить PictureBox в файл jpg без вызова диалога сохранения
как сохранить изображение на PictureBox в файл .jpg без вызова диалога сохранения

1
9 / 9 / 1
Регистрация: 01.09.2010
Сообщений: 182
09.12.2011, 21:18 2
Можно попробовать сохранить в BMP формате, а в имени файла дать разрешение JPG.
Просто при повторном сохранение программа по-новой сжимает изображение, потому что JPG это сжатое изображение.....
0
09.12.2011, 21:18
IT_Exp
Эксперт
87844 / 49110 / 22898
Регистрация: 17.06.2006
Сообщений: 92,604
09.12.2011, 21:18
Помогаю со студенческими работами здесь

Как, не меняя и не переставляя главный EXE-файл, при его запуске запускать другие программы?
Здравствуйте! Задачка такая. Есть у меня файл, скажем &quot;D:\Files\example.exe&quot;. Нужно сделать так,...

Сохранить файл *.jpg в таблице Paradox
Возникла проблема: Есть база данных с таблицей PARADOX7 (файлы с расширениями *.DB и *.MB), нужно...

На листе находится рисунок; можно ли сохранить этот рисунок из книги, как отдельный bmp или jpg файл?
1. На листе находится рисунок. Можно ли, сохранить этот рисунок из книги как отделений Bmp или jpg...

Сохранить содержимое webbrowser в файл (jpg или bmp)
Есть элемент webbrowser с содержимым. Как сохранить содержимое в файл указанного формат, например...


Искать еще темы с ответами

Или воспользуйтесь поиском по форуму:
2
Ответ Создать тему
Опции темы

КиберФорум - форум программистов, компьютерный форум, программирование
Powered by vBulletin
Copyright ©2000 - 2024, CyberForum.ru