This question has already been answered:

This code snatches the image on the bottom. Save to a file with the same name does not give due to an error using the file. Therefore, I created a temporary file with the tmp extension. The problem occurs when deleting - due to the fact that the resource fileName is busy. How to release him correctly?

 byte[] photoBytes = File.ReadAllBytes(fileName); // для чтения FileStream fs = File.OpenWrite(fileName+".tmp"); // для записи using (MemoryStream inStream = new MemoryStream(photoBytes)) { using (MemoryStream outStream = new MemoryStream()) { using (ImageFactory imageFactory = new ImageFactory(preserveExifData: true)) { Image tmp = new Bitmap(Image.FromFile(fileName)); imageFactory.Load(inStream) // грузим картинку .Crop(new Rectangle(0, 0, tmp.Width, tmp.Height - 62)) .Save(outStream); // сохраняем в поток outStream.WriteTo(fs); // записываем в файл outStream.Close(); // не забываем закрывать потоки ввода-вывода } inStream.Close(); // не забываем закрывать потоки ввода-вывода fs.Close(); } } File.Delete(fileName); File.Move(fileName+".tmp", fileName); 

Reported as a duplicate by the participants iluxa1810 , user194374, PashaPash c # Feb 25 '17 at 12:17 .

A similar question was asked earlier and an answer has already been received. If the answers provided are not exhaustive, please ask a new question .

1 answer 1

Why so many things if it's a simple Crop. Try this:

 string fileName = "2.png"; byte[] photoBytes = File.ReadAllBytes(fileName); // для чтения using (FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.ReadWrite)) // для записи { using (MemoryStream inStream = new MemoryStream(photoBytes)) { ImageFactory imageFactory = new ImageFactory(true); var tmp = Image.FromStream(fs); var cropImg = imageFactory.Load(inStream).Crop(new Rectangle(0, 0, tmp.Width, tmp.Height - 300)); inStream.Position = 0; cropImg.Save(inStream); fs.Position = 0; inStream.CopyTo(fs); } } 

I would make it even easier:

 public static void Main(string[] args) { string fileName = "5.png"; byte[] photoBytes = File.ReadAllBytes(fileName); using (FileStream fs = File.Open(fileName, FileMode.Open, FileAccess.ReadWrite)) { ImageFactory imageFactory = new ImageFactory(true); var tmp = Image.FromStream(fs); var cropImg = imageFactory.Load(photoBytes).Crop(new Rectangle(0, 0, tmp.Width, tmp.Height - 300)); fs.Position = 0; cropImg.Save(fs); } }