|
| 1 | +using System; |
| 2 | +using System.Drawing; |
| 3 | +using System.Drawing.Imaging; |
| 4 | +using System.IO; |
| 5 | + |
| 6 | +namespace IMDbAPI_Client |
| 7 | +{ |
| 8 | + public class ClientUtils |
| 9 | + { |
| 10 | + public static byte[] ImageToBytes(Image img) |
| 11 | + { |
| 12 | + return ImageToBytes(img, ImageFormat.Png); |
| 13 | + } |
| 14 | + |
| 15 | + public static byte[] ImageToBytes(Image img, Size size) |
| 16 | + { |
| 17 | + if (img == null) |
| 18 | + return null; |
| 19 | + |
| 20 | + if (img.Width > size.Width || img.Height > size.Height) |
| 21 | + img = ResizeImage(img, size); |
| 22 | + |
| 23 | + return ImageToBytes(img, ImageFormat.Png); |
| 24 | + } |
| 25 | + |
| 26 | + public static byte[] ImageToBytes(Image img, ImageFormat imgFormat) |
| 27 | + { |
| 28 | + if (img == null) |
| 29 | + return null; |
| 30 | + |
| 31 | + var ms = new MemoryStream(); |
| 32 | + img.Save(ms, imgFormat); |
| 33 | + return ms.ToArray(); |
| 34 | + } |
| 35 | + |
| 36 | + public static Image BytesToImage(byte[] bytes) |
| 37 | + { |
| 38 | + if (bytes == null) |
| 39 | + return null; |
| 40 | + |
| 41 | + var ms = new MemoryStream(bytes); |
| 42 | + var returnImage = Image.FromStream(ms); |
| 43 | + return returnImage; |
| 44 | + } |
| 45 | + |
| 46 | + public static Image BytesToImage(byte[] bytes, Size size) |
| 47 | + { |
| 48 | + if (bytes == null) |
| 49 | + return null; |
| 50 | + |
| 51 | + var img = BytesToImage(bytes); |
| 52 | + if (img.Width > size.Width || img.Height > size.Height) |
| 53 | + return ResizeImage(img, size); |
| 54 | + |
| 55 | + return img; |
| 56 | + } |
| 57 | + |
| 58 | + public static Image ResizeImage(Image img, Size size) |
| 59 | + { |
| 60 | + var ratioX = (double)size.Width / img.Width; |
| 61 | + var ratioY = (double)size.Height / img.Height; |
| 62 | + var ratio = Math.Min(ratioX, ratioY); |
| 63 | + |
| 64 | + var newWidth = (int)(img.Width * ratio); |
| 65 | + var newHeight = (int)(img.Height * ratio); |
| 66 | + |
| 67 | + var newImage = new Bitmap(newWidth, newHeight); |
| 68 | + |
| 69 | + using (var graphics = Graphics.FromImage(newImage)) |
| 70 | + graphics.DrawImage(img, 0, 0, newWidth, newHeight); |
| 71 | + |
| 72 | + return newImage; |
| 73 | + } |
| 74 | + } |
| 75 | +} |
0 commit comments