Здравствуйте, есть изображение допустим jpg которое открыто при помощи блокнота и данный текст скопирован в другой текстовый документ и сохранен как jpg. Вопрос почему изображение не открывается как исходное? Как возможно данное изображение считать из текста? И если использовать побайтное чтение и запись из сохраненного текстового файла тоже не получается.
-
сравните по байтам два документа (не в текстовом редакторе, конечно, а чем-нибудь типа "Hex View" в Far'e или кодом) - и увидите– user17626218 ноя 2016 в 4:45
-
Понял спасибо. Нашел различия сейчас попробую еще раз считать файл побайтово.– Taras M.18 ноя 2016 в 4:59
-
Текстовый редактор мог добавить BOM в зависимости от кодировки.– Alexander Petrov18 ноя 2016 в 6:22
2 ответа
Нашел ответ в интернете на свой вопрос с сервиса: https://halluphigh.wordpress.com/2010/08/26/extracting-a-jpeg-image-from-any-file-using-c/
В этом коде используются магические числа для обозначения начал и конца файла для jpeg это 0xFF и 0xD8 не сложно найти и для других форматов брал отсюда: https://en.wikipedia.org/wiki/List_of_file_signatures
сам код ответа:
/Remove the excess data in given file and returns the new location of the modified file and
//returns an empty string if no file was created.
public static string StripExcessDataFromJpeg(string fileLocation)
{
//if no image is found in the file, it will return this error message
string newFileName = "";
BinaryReader br = new BinaryReader(File.Open(fileLocation, FileMode.Open));
try
{
bool done = false;
long count = 0;
//The file must be read until the end of the file (in which case there was no image)
//or until the jpeg file is found.
while ((count < br.BaseStream.Length) && !done)
{
//has to be read one at a time so not to consume more than needed
count++;
if (br.ReadByte() == 0xFF)
{
count++;
if (br.ReadByte() == 0xD8)
{
done = true;
newFileName = fileLocation + ".jpg";
WriteJpegBinaryToFile(newFileName, br);
}
}
}
}
catch (Exception)
{
Console.WriteLine("File format not found.");
//File name set back to empty to indicate the file wasn't created.
newFileName = "";
}
br.Close();
return newFileName;
}
private static void WriteJpegBinaryToFile(string fileName, BinaryReader br)
{
FileStream fs = File.Create(fileName);
//write back the jpeg header already consumed in the stream
byte[] jpegHeader = { 0xFF, 0xD8 };
fs.Write(jpegHeader, 0, jpegHeader.Length);
long count = 0;
while (count < br.BaseStream.Length)
{
long bytesToRead = 1024; //Read 1kb at a time, increase if dealing with larger files.
if (bytesToRead + count > br.BaseStream.Length)
{
bytesToRead = br.BaseStream.Length - count;
}
byte[] bytes = new byte[bytesToRead];
br.Read(bytes, 0, bytes.Length);
count += bytesToRead;
fs.Write(bytes, 0, bytes.Length);
}
fs.Close();
}
Текстовый редактор может игнорировать не печатные символы, то есть ASCII коды которых меньше 32, за исключение перевода строки и табуляции. Скорее всего он не копирует их в буфер.
Используйте для копирования части файла какой-нибудь бинарный редактор.