Xamarin.Android 壓縮圖片並上傳到WebServices


  隨着手機的拍照像素越來越高,導致圖片贊的容量越來越大,如果上傳多張圖片不進行壓縮、質量處理很容易出現OOM內存泄漏問題。

  最近做了一個項目,向webservices上傳多張照片,但是項目部署出來就會出現閃退現象,后來經行調試發現圖片沒有進行壓縮,一張圖片大小為2M,然而webservices沒法接搜多個大圖片,所以需要改下配置文件,我這里改為40M。

  <system.web> 
    <httpRuntime maxRequestLength = "40960" useFullyQualifiedRedirectUrl="true"/>
  </system.web>

   這里改好后發現上傳圖片還是有問題,后來經過一步步調試發現將本地圖片轉換成Bitmap后沒有清空,然后一直存放在內存中,導致內存泄漏。只要把轉換完的Bitmap清空一下就好了。

        /// <summary>
        /// 圖片轉換成String流
        /// </summary>
        /// <param name="file_path">文件名(不帶file://)</param>
        /// <returns></returns>
        public static string ImageToString(string file_path)
        {
            //待上傳圖片路徑
            //string uploadFile = file_path;

            //轉化成文件  

            //System.IO.FileInfo imgFile = new System.IO.FileInfo(uploadFile);



            ////文件轉化成字節
            //byte[] imgByte = new byte[imgFile.Length];

            //////讀文件               
            //System.IO.FileStream imgStream = imgFile.OpenRead();

            //////文件寫入到字節數組
            //imgStream.Read(imgByte, 0, Convert.ToInt32(imgFile.Length));

            //////字節數組轉換成String類型
            //string by = Convert.ToBase64String(imgByte);

            ////上傳到服務器 后面是文件名 
            ////fileUp.UpdateFile(imgByte, Guid.NewGuid() + ".png");

            //return imgByte;  

            Bitmap bitmap = BitmapFactory.DecodeFile(file_path);        //將圖片文件轉換成bitmap 格式:/storage/emulated/0/DCIM/Camera/IMG_20180425_105725.jpg

            string bitstring = BitmapToString(bitmap); 
            bitmap = null;              //一定要清空,否則會導致OOM問題
            GC.Collect();
            return bitstring; 
        } 

        /// <summary>
        /// 圖片縮放處理
        /// </summary>
        /// <param name="bgimage">Bitmap文件</param>
        /// <param name="newWidth">新圖片寬度</param>
        /// <param name="newHeight">新圖片高度</param>
        /// <returns></returns>
        public static Bitmap zoomImage(Bitmap bgimage, double newWidth, double newHeight)
        {
            // 獲取這個圖片的寬和高
            float width = bgimage.Width;
            float height = bgimage.Height;
            // 創建操作圖片用的matrix對象
            Matrix matrix = new Matrix();
            // 計算寬高縮放率
            float scaleWidth = ((float)newWidth) / width;
            float scaleHeight = ((float)newHeight) / height;
            // 縮放圖片動作
            matrix.PostScale(scaleWidth, scaleHeight);
            Bitmap bitmap = Bitmap.CreateBitmap(bgimage, 0, 0, (int)width,
                            (int)height, matrix, true);
            return bitmap;
        }

        static  string  BitmapToString(Bitmap bitmap)
        {
            Bitmap bit = zoomImage(bitmap, 750, 1000);//小圖
                                                   //質量壓縮
            //MemoryStream stream = new MemoryStream();
            //bit.Compress(Bitmap.CompressFormat.Jpeg, 50, stream);
            //byte[] bitmapData = stream.ToArray();
            //Bitmap map = BitmapFactory.DecodeByteArray(bitmapData, 0, bitmapData.Length);
            //btn_imagetwo.SetImageBitmap(map);
            //Bitmap im = zoomImage(bitmap, 800, 900);//大圖
            MemoryStream big_stream = new MemoryStream();
            bit.Compress(Bitmap.CompressFormat.Jpeg, 80, big_stream);
            byte[] big_bitmapData = big_stream.ToArray();
            return  Convert.ToBase64String(big_bitmapData);
        }        

  webservices接受進行保存圖片:

     private String ImagePath = "/HandlerImages/";

        /// <summary>
        /// 上傳圖片
        /// </summary>
        /// <param name="content">圖片字符流</param>
        /// <param name="pathandname">圖片名稱</param>
        /// <returns></returns>
        
        [WebMethod]
        public bool UpdateFile(string content, string pathandname)
        {
            //保存圖片路徑
            string FilePath = Server.MapPath(ImagePath);
            //判斷路徑是否存在
            if (!Directory.Exists(FilePath))
            {
                //創建路徑
                Directory.CreateDirectory(FilePath);
            }

            string SaveFilePath = Path.Combine(FilePath, pathandname);
            byte[] fileBytes;
            try
            {
                fileBytes = Convert.FromBase64String(content);
                MemoryStream memoryStream = new MemoryStream(fileBytes); //1.定義並實例化一個內存流,以存放提交上來的字節數組。  
                FileStream fileUpload = new FileStream(SaveFilePath, FileMode.Create); ///2.定義實際文件對象,保存上載的文件。  
                memoryStream.WriteTo(fileUpload); ///3.把內存流里的數據寫入物理文件  
                memoryStream.Close();
                fileUpload.Close();
                fileUpload = null;
                memoryStream = null;
                return true;
            }
            catch
            {
                return false;
            }
        }

調用webservices上傳圖片:

MyWebService service = new MyWebService(); 
service.UpdateFile(ImageToByte("/storage/emulated/0/DCIM/Camera/IMG_20180425_105725.jpg"),Guid.NewGuid().ToString() + ".jpg");

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM