You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

79 lines
2.7 KiB

  1. using Common.Utility;
  2. using System;
  3. using System.Drawing;
  4. using System.Drawing.Imaging;
  5. using System.IO;
  6. namespace Repository.DAO.Utility
  7. {
  8. public class ImageCompressDao : RemittanceDao
  9. {
  10. public bool CompressImageAndSave(long contentLength, string orgImageSource, string tmpFilePath)
  11. {
  12. try
  13. {
  14. Image original = Image.FromFile(orgImageSource);
  15. ImageCodecInfo jpgEncoder = null;
  16. ImageCodecInfo[] codecs = ImageCodecInfo.GetImageEncoders();
  17. foreach (ImageCodecInfo codec in codecs)
  18. {
  19. if (codec.FormatID == ImageFormat.Jpeg.Guid)
  20. {
  21. jpgEncoder = codec;
  22. break;
  23. }
  24. }
  25. if (jpgEncoder != null)
  26. {
  27. Encoder encoder = Encoder.Quality;
  28. EncoderParameters encoderParameters = new EncoderParameters(1);
  29. var suggestedImage = GetSuggestedImage(contentLength, original.Height, original.Width);
  30. EncoderParameter encoderParameter = new EncoderParameter(encoder, long.Parse(suggestedImage.Id));
  31. encoderParameters.Param[0] = encoderParameter;
  32. string fileOut = tmpFilePath;
  33. FileStream ms = new FileStream(fileOut, FileMode.Create, FileAccess.ReadWrite);
  34. try
  35. {
  36. original.Save(ms, jpgEncoder, encoderParameters);
  37. }
  38. catch (Exception)
  39. {
  40. }
  41. finally
  42. {
  43. ms.Flush();
  44. ms.Close();
  45. original.Dispose();
  46. if (File.Exists(orgImageSource))
  47. File.Delete(orgImageSource);
  48. }
  49. }
  50. return true;
  51. }
  52. catch (Exception)
  53. {
  54. return false;
  55. }
  56. }
  57. public DbResult GetSuggestedImage(long imageSize, int height, int width)
  58. {
  59. string sql = "EXEC proc_getSuggestedImage @flag=si";
  60. sql += ", @imgActualSize = " + FilterString(imageSize.ToString());
  61. sql += ", @imgActualHight = " + FilterString(height.ToString());
  62. sql += ", @imgActualWidth = " + FilterString(width.ToString());
  63. return ParseDbResult(sql);
  64. }
  65. }
  66. public class Pic
  67. {
  68. public string Description;
  69. public string FilePath;
  70. public bool IsSuggested = false;
  71. }
  72. }