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