随着手机的拍照像素越来越高,导致图片赞的容量越来越大,如果上传多张图片不进行压缩、质量处理很容易出现OOM内存泄漏问题。

  最近做了一个项目,向webservices上传多张照片,但是项目部署出来就会出现闪退现象,后来经行调试发现图片没有进行压缩,一张图片大小为2M,然而webservices没法接搜多个大图片,所以需要改下配置文件,我这里改为40M。

  <system.web>
<httpRuntime maxRequestLength = "" 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, , , (int)width,
(int)height, matrix, true);
return bitmap;
} static string BitmapToString(Bitmap bitmap)
{
Bitmap bit = zoomImage(bitmap, , );//小图
//质量压缩
//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, , 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");

Xamarin.Android 压缩图片并上传到WebServices的更多相关文章

  1. 使用canvas压缩图片 并上传

    <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title> ...

  2. ios中摄像头/相册获取图片,压缩图片,上传服务器方法总结

    相册 iphone的相册包含摄像头胶卷+用户计算机同步的部分照片.用户可以通过UIImagePickerController类提供的交互对话框来从相册中选择图像.但是,注意:相册中的图片机器路径无法直 ...

  3. HTML5 Canvas前台压缩图片并上传到服务器

    1.前台代码: <input id="fileOne" type="file" /> <input id="btnOne" ...

  4. js压缩图片并上传,不失真,保证图片清晰度

    <!DOCTYPE HTML> <html lang="zh-CN"> <head> <meta charset="UTF-8& ...

  5. html5压缩图片并上传

    手机端图片有很大的,上传的时候很慢,这时候就要压缩一下了,有一个开源的js可以压缩图片的大小,开源地址如下:https://github.com/think2011/localResizeIMG3 代 ...

  6. Xamarin.Android 使用AsyncTask提示上传动态

    我们有时候会通过WebServices上传数据,如果信息量过大并没有提示,用户会觉得是死机,或是系统崩溃,这时候我们可以用到AsyncTask(异步任务)来提示上传信息,例如:正在上传数据... 这里 ...

  7. javaScript:压缩图片并上传

    html代码: <input id="file" type="file" name="filesName"> js代码: var ...

  8. 微信小程序 压缩图片并上传

    转自https://segmentfault.com/q/1010000012507519 wxml写入 <view bindtap='uploadImg'>上传</view> ...

  9. 微信小程序压缩图片并上传到服务器(拿去即用)

    这里注意一下,图片压缩后的宽度是画布宽度的一半 canvasToTempFilePath 创建画布的时候会有一定的时间延迟容易失败,这里加setTimeout来缓冲一下 这是单张图片压缩,多张的压缩暂 ...

随机推荐

  1. Failed to connect to /127.0.0.1:8080

    参考 https://blog.csdn.net/qq_36523667/article/details/78823065 127.0.0.1为虚拟机的地址,需要将地址改为本机实际地址  ipconf ...

  2. socket failed: EACCES

    参考 https://blog.csdn.net/ct_ts/article/details/80010208 <uses-permission android:name=“android.pe ...

  3. c++ 面试题(C/C++/STL)

    1,智能指针:auto_ptr(c++11 已经弃用),unique_ptr(用于取代 auto_ptr),  shared_ptr,  weak_ptr http://www.cnblogs.com ...

  4. Python中import, from...import,import...as的区别

    import datetime print(datetime.datetime.now()) 以上代码实现输出系统当前时间,是引入整个datetime包,然后再调用datetime这个类中的now() ...

  5. related_name和related_query_name举例区别

    例1: class UserInfo(models.Model): nickname = models.CharField(max_length=32) username = models.CharF ...

  6. Python开发——基础

    注释 单行注释 # 被注释的内容 多行注释 """ 被注释的内容 """ 解释器路径 #!/usr/bin/env python # 用于L ...

  7. js判断手机系统(Android或IOS),跳转相应下载地址

    <script type="text/javascript"> $(document).ready(function(e) { var u = navigator.us ...

  8. nginx的https代理http配置

    http { upstream https2http_proxy{ server 192.168.22.103:80; } server { listen 1443 ssl; server_name ...

  9. Python11/12--GIL/互斥锁/进程池

    GIL1.全局解释器锁? 锁就是线程里面那个锁 锁是为了避免资源竞争造成数据的错乱 2.python程序的执行过程? 1.启动解释器进程 python.exe 2.解析你的py文件并执行它 每个py程 ...

  10. ios 导航push跳转方向设置

    CATransition* transition = [CATransition animation]; transition.type = kCATransitionPush;//可更改为其他方式 ...