using System; using System.Diagnostics; using System.Drawing; using System.Drawing.Drawing2D; using System.Drawing.Imaging; using System.IO; using System.Linq; namespace ChatController.Utilities { public class FileUtils { public static string ScaleImage(string pFile, string pFormat, long maxUploadSize) { var isImageFile = Constants.ImageFileExtensions.Contains(Path.GetExtension(pFile).ToUpperInvariant()); if(!isImageFile) { return pFile; } byte[] mediaFile; using(Stream reader = File.OpenRead(pFile)) { mediaFile = Utils.ReadFully(reader); } var memoryStream = new MemoryStream(mediaFile); var image = Image.FromStream(memoryStream); float width, height; if(image.Height < image.Width) { if(image.Height > 1080) { var factor = (float)image.Height / 1080; height = 1080; width = image.Width / factor; } else { return pFile; } } else if(image.Height < 1080 && image.Width < 1080) { return pFile; } else { if(image.Width > 1080) { var factor = (float)image.Width / 1080; width = 1080; height = image.Height / factor; } else { return pFile; } } var scaledBitmap = new Bitmap(image, new Size((int)width, (int)height)); const int orientationId = 0x0112; if(image.PropertyIdList.Contains(orientationId)) { var item = image.GetPropertyItem(orientationId); scaledBitmap.SetPropertyItem(item); } using(var graphics = Graphics.FromImage(image)) { graphics.Clear(Color.Transparent); graphics.InterpolationMode = InterpolationMode.Low; graphics.DrawImage(scaledBitmap, (int)width, (int)height); } // tmp_img_owch_ var filePath = $"{Path.GetTempPath()}{Guid.NewGuid()}_tmp_img_owch{pFormat}"; if(pFormat.Equals(".JPG") || pFormat.Equals(".JPE") || pFormat.Equals(".JPEG") || pFormat.Equals(".BMP")) { scaledBitmap.Save(filePath, ImageFormat.Jpeg); } else if(pFormat.Equals(".PNG")) { scaledBitmap.Save(filePath, ImageFormat.Png); } else if(pFormat.Equals(".GIF")) { scaledBitmap.Save(filePath, ImageFormat.Gif); } if(File.Exists(filePath)) { var fileInfo = new FileInfo(filePath); var fileInfoLength = fileInfo.Length; if(maxUploadSize < fileInfoLength) { File.Delete(filePath); return string.Empty; } } else { return string.Empty; } memoryStream.Dispose(); memoryStream.Close(); return filePath; } public static bool CheckFileSize(string pathToFile, long maxFileSize) { var fileInfo = new FileInfo(pathToFile); return fileInfo.Length > maxFileSize; } public static bool IsFileLocked(string path) { if(!File.Exists(path)) { return false; } try { var file = new FileInfo(path); using (var stream = file.Open(FileMode.Open, FileAccess.Read, FileShare.None)) { stream.Close(); } } catch(IOException ioException) { Debug.WriteLine($"Error (FileUtils.IsFileLocked): {ioException.Message}"); return true; } return false; } } }