1. 程式人生 > >上傳壓縮後的圖片並且保持100k不失真的方法

上傳壓縮後的圖片並且保持100k不失真的方法

壓縮100k圖片不失真的方法;先獲取圖片的原始長度和寬度;然後計算圖片的縮放值;最後等比例壓縮;

下面程式碼是壓縮的工具類;

public class PictureUtil {


	/**
	 * 主方法
	 * 
	 * @param filePath
	 * @return
	 */
	public static InputStream bitmapToString(String filePath) {

		Bitmap bm = getSmallBitmap(filePath);

		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		bm.compress(Bitmap.CompressFormat.JPEG, 60, baos);
		// 把壓縮後的資料baos存放到ByteArrayInputStream中
		ByteArrayInputStream isBm = new ByteArrayInputStream(
				baos.toByteArray());
		return isBm;
	}

	/**
	 * 計算圖片的縮放值
	 * 
	 * @param options
	 * @param reqWidth
	 * @param reqHeight
	 * @return
	 */
	public static int calculateInSampleSize(BitmapFactory.Options options,
			int reqWidth, int reqHeight) {
		// Raw height and width of image
		final int height = options.outHeight;
		final int width = options.outWidth;
		int inSampleSize = 1;

		if (height > reqHeight || width > reqWidth) {

			// Calculate ratios of height and width to requested height and
			// width
			final int heightRatio = Math.round((float) height
					/ (float) reqHeight);
			final int widthRatio = Math.round((float) width / (float) reqWidth);

			// Choose the smallest ratio as inSampleSize value, this will
			// guarantee
			// a final image with both dimensions larger than or equal to the
			// requested height and width.
			inSampleSize = heightRatio < widthRatio ? heightRatio : widthRatio;
		}

		return inSampleSize;
	}




	/**
	 * 根據路徑獲得突破並壓縮返回bitmap用於顯示
	 * 
	 * @param imagesrc
	 * @return
	 */
	public static Bitmap getSmallBitmap(String filePath) {
		final BitmapFactory.Options options = new BitmapFactory.Options();
		options.inJustDecodeBounds = true;
		BitmapFactory.decodeFile(filePath, options);

		// Calculate inSampleSize
		options.inSampleSize = calculateInSampleSize(options, 800, 480);

		// Decode bitmap with inSampleSize set
		options.inJustDecodeBounds = false;

		return BitmapFactory.decodeFile(filePath, options);
	}

	/**
	 * 根據路徑刪除圖片
	 * 
	 * @param path
	 */
	public static void deleteTempFile(String path) {
		File file = new File(path);
		if (file.exists()) {
			file.delete();
		}
	}

	/**
	 * 新增到相簿
	 */
	public static void galleryAddPic(Context context, String path) {
		Intent mediaScanIntent = new Intent(
				Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
		File f = new File(path);
		Uri contentUri = Uri.fromFile(f);
		mediaScanIntent.setData(contentUri);
		context.sendBroadcast(mediaScanIntent);
	}

	/**
	 * 獲取儲存圖片的目錄
	 * 
	 * @return
	 */
	public static File getAlbumDir() {
		File dir = new File(
				Environment
				.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),
				getAlbumName());
		if (!dir.exists()) {
			dir.mkdirs();
		}
		return dir;
	}

	/**
	 * 獲取儲存 隱患檢查的圖片資料夾名稱
	 * 
	 * @return
	 */
	public static String getAlbumName() {
		return "sheguantong";
	}
}

下面是上傳圖片的工具類;只需要提供圖片url就可以了;
**
 * 
 * 上傳工具類上傳壓縮;
 * @author spring sky
 * Email:[email protected]
 * QQ:840950105
 * MyName:石明政
 */
public class UploadUtil {
	private static final String TAG = "uploadFile";
	private static final int TIME_OUT = 10*1000;   //超時時間
	private static final String CHARSET = "utf-8"; //設定編碼
	/**
	 * android上傳檔案到伺服器
	 * @param file  需要上傳的檔案
	 * @param RequestURL  請求的rul
	 * @return  返回響應的內容
	 */
	public static String uploadFile(String file,String RequestURL)
	{
		String result = null;
		String  BOUNDARY =  UUID.randomUUID().toString();  //邊界標識   隨機生成
		String PREFIX = "--" , LINE_END = "\r\n"; 
		String CONTENT_TYPE = "multipart/form-data";   //內容型別

		try {
			URL url = new URL(RequestURL);
			HttpURLConnection conn = (HttpURLConnection) url.openConnection();
			conn.setReadTimeout(TIME_OUT);
			conn.setConnectTimeout(TIME_OUT);
			conn.setDoInput(true);  //允許輸入流
			conn.setDoOutput(true); //允許輸出流
			conn.setUseCaches(false);  //不允許使用快取
			conn.setRequestMethod("POST");  //請求方式
			conn.setRequestProperty("Charset", CHARSET);  //設定編碼
			conn.setRequestProperty("connection", "keep-alive");   
			conn.setRequestProperty("Content-Type", CONTENT_TYPE + ";boundary=" + BOUNDARY); 

			if(file!=null){
				/**
				 * 當檔案不為空,把檔案包裝並且上傳
				 */
				DataOutputStream dos = new DataOutputStream(conn.getOutputStream());
				InputStream is =PictureUtil.bitmapToString(file);
				byte[] bytes = new byte[9000];
				int len = 0;
				while((len=is.read(bytes))!=-1){
					dos.write(bytes, 0, len);
				}
				is.close();
				dos.write(LINE_END.getBytes());
				byte[] end_data = (PREFIX+BOUNDARY+PREFIX+LINE_END).getBytes();
				dos.write(end_data);
				dos.flush();
				/**
				 * 獲取響應碼  200=成功
				 * 當響應成功,獲取響應的流  
				 */
				int res = conn.getResponseCode();  
				Log.e(TAG, "response code:"+res);
				//                if(res==200)
				//                {
				Log.e(TAG, "request success");
				InputStream input =  conn.getInputStream();
				StringBuffer sb1= new StringBuffer();
				int ss ;
				while((ss=input.read())!=-1)
				{
					sb1.append((char)ss);
				}
				result = sb1.toString();
				Log.e(TAG, "result : "+ result);
				//                }
				//                else{
				//                    Log.e(TAG, "request error");
				//                }
			}
		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return result;
	}



	public static InputStream compressImage(String file) {
		Bitmap bitmap = BitmapFactory.decodeFile(file);
		BitmapFactory.Options newOpts = new BitmapFactory.Options();
		// 開始讀入圖片,此時把options.inJustDecodeBounds設為true
		newOpts.inJustDecodeBounds = true;
		bitmap = BitmapFactory.decodeFile(file, newOpts);
		newOpts.inJustDecodeBounds = false;
		int w = newOpts.outWidth;
		int h = newOpts.outHeight;
		// 設定解析度
		float hh = 800f;
		float ww = 400f;
		// 縮放比。由於是固定的比例縮放,只用高或者寬其中一個數據進行計算即可
		int be = 1;
		if (w > h && w > ww) {// 如果寬度大的話根據寬度固定大小縮放
			be = (int) (newOpts.outWidth / ww);
		} else if (w < h && h > hh) {// 如果寬度大的話根據寬度固定大小縮放
			be = (int) (newOpts.outHeight / hh);
		}
		if (be <= 0) {
			be = 1;
		}
		newOpts.inSampleSize = be;// 設定縮放比例
		// 重新讀入圖片,注意此時已經把newOpts.inJustDecodeBounds = false
		bitmap = BitmapFactory.decodeFile(file, newOpts);
		try {
			//			Bitmap bitmapyas=compressImage1(bitmap);
			return compressImage2(bitmap);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return null;
		}
	}

	public static InputStream compressImage2(Bitmap bitmap) throws Exception {
		try {
			ByteArrayOutputStream baos = new ByteArrayOutputStream();
			bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
			int options = 100;
			int size = baos.toByteArray().length / 1024;
			while (size > 40 && options > 0) {
				baos.reset();// 重置baos即清空baos
				options -=10;// 每次都減少10
				// 這裡壓縮options%,把壓縮後的資料存放到baos中
				bitmap.compress(Bitmap.CompressFormat.JPEG, options, baos);
				size = baos.toByteArray().length / 1024;
			}
			// 把壓縮後的資料baos存放到ByteArrayInputStream中
			ByteArrayInputStream isBm = new ByteArrayInputStream(
					baos.toByteArray());
			return isBm;

		} catch (Exception e) {
			throw e;
		}
	}
}



相關推薦

壓縮圖片並且保持100k失真方法

壓縮100k圖片不失真的方法;先獲取圖片的原始長度和寬度;然後計算圖片的縮放值;最後等比例壓縮; 下面程式碼是壓縮的工具類; public class PictureUtil { /** * 主方法 * * @param filePath * @r

Android中相機拍攝照片,以及相簿選擇圖片壓縮(壓縮儲存進SD中)(可用於修改頭像等)

           這個功能借鑑了多個大神的,然後整合起來。                    Android中相機拍攝照片,以及相簿選擇圖片壓縮上傳(壓縮後儲存進SD中)(可用   於修改頭像等)                       第一步: privat

一款簡單實用的文件圖片插件並且兼容移動端zyupload.js

png http ext 選中 nis blog onf 1-1 text 1.下載zyupload插件包 包含的文件如下圖: 2.在/images/fileType文件夾下定義上傳文件的顯示圖標 如下圖所示: 3.打開zyupload.js,修改上傳後顯示文件圖標

vue-cli 關於圖片頭像壓縮的插件

ade -c init 問題 scrip file image() idt 判斷圖片 安裝插件 exif-js 1 <template> 2 <div> 3 <div style="padding:20px

阿里雲 javascript檔案(圖片、視訊、壓縮包等檔案)到 物件儲存 OSS ,返回檔案、圖片、音訊、視訊等URL路徑

目的:前端上傳檔案(圖片、視訊、音訊等)到阿里雲伺服器裡面,並且獲得上傳檔案的URL路徑 前提:首先要買一個阿里雲伺服器,自己百度不會; 第一步:登入阿里雲賬號,點選管理控制檯-->物件儲存 OSS 第二步:新建儲存空間(圖一、圖二) (圖一) (圖二

圖片壓縮校正

import Exif from 'exif-js'; /* eslint-disable func-names */ function ImageProcess(file, callback) { let Orientation; // 去獲取拍照時的資訊,解決拍出來的照片旋轉問題 Exi

java 檔案 、圖片 壓縮

圖片壓縮,在我的想法裡面有下面幾個要求。 1、壓縮程度可控制,想壓縮成多小就多小。 2、壓縮之後圖片儘可能的不失真。 3、壓縮速度要快。 4、程式碼簡單,依賴較少。 實現 然後帶著這

關於php多張圖片時,選擇圖片就可以預覽的問題

這幾天一直在解決一個問題,上傳圖片時選擇成功後就能預覽。 需求:在點選上傳圖示的時候會在前面的input框中顯示出檔名,然後點選後面的檢視按鈕就可以預覽選擇的這張圖片了,要求不能重新整理頁面 1.一開始的時候打算用ajax上傳,後來發現多張圖片一同上傳的時候會出現問題,a

HTML5實現input:file壓縮,等比壓縮圖片、base64和檔案互相轉換

本文例項為大家分享了Vue2.0實現呼叫攝像頭進行拍照功能的具體程式碼,以及圖片上傳功能引用exif.js,供大家參考,具體內容如下 外掛: 1.jquery.min.js 2.exif.js 效果目標:實現等比例壓縮上傳 上程式碼 HTML <!DO

Java手機拍攝圖片矯正方向

package useractivity.utils; import com.drew.imaging.ImageMetadataReader; import com.drew.metadata.Directory; import com.drew.metadata.Metadata; imp

java多張圖片並且可以刪除圖片

如果你想只上傳一張圖片:http://blog.csdn.net/xuanzhangran/article/details/54928997 上傳多張: 可以刪除從庫裡查詢出來的圖片,也可以刪除剛上傳到圖片,其實不多,為了任務請耐心看完: 效果如下: 1

前端多張圖片壓縮

html:<input type="file" id="choose" accept="image/*" multiple>   //multiple屬性允許上傳多張js:$("#choose").change(function() { // 上傳事件觸發if (

jsp圖片到資料庫,並且實現取出來

說明:基於jsp與servlet、mysql對的圖片的上傳與操作,servlet用於操作檔案的上傳。實現上傳需要包檔案:commons-fileupload-1.3.2、commons-io-2.5.jar、mysql-connector-java5.1.26-bin.jar

iOS多張圖片多執行緒處理方法(可獲取最後一張狀態的訊號)

環境重現 1,服務端提供單張上傳的介面。 2,客戶端需求同時提交多張圖片上傳。 3,使用AFNetWorking 或 自封裝的帶有block回撥網路狀態的框架。 思路 1,建立一個管理類。 2,提供一個單例方法。保證管理類唯一 3,提供一個公共

移動端(h5),壓縮,預覽圖片

專案裡邊這次用到了移動端上傳圖片,拿出來分享下。 1.首先是思路,在input 發生change的時候判斷瀏覽器時候支援圖片預覽,支援的情況下校驗圖片的格式,圖片的大小,之後將拿到的圖片進行canvas壓縮,圖片轉base64,然後上傳。 2.程式碼

django將圖片資料庫在前端顯式

1、使用ImageField先安裝pillow模組 pip install pillow 2、在app的models中設定 class Image(models.Model): pic_name=models.CharField('圖片

前端多張圖片,編譯發給

今天分享一個找上傳多張圖片的方法,使用於網頁,移動端。 HTML頁面 <fieldset>   <legend>瀏覽圖片檔案:</legend>   <input type='file' name='fleUpload' id='f

使用json方式圖片時,發現成功,變成下載了json... 或者無法解析到返回的結果集!!!

問題描述:如題 PS:使用Struts框架!!! 解決方案: <result name="typename" type="json"><param name="noCache">true</param><param name="

改進的顯示照片(可以剪下,圓形的圖片

@Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCo

、裁剪圖片-----Jcrop圖片裁剪插件

.com class 選擇圖片 sel oca put 新的 mage htm Jcrop文檔:http://code.ciaoca.com/jquery/jcrop/C#裁剪:http://www.cnblogs.com/xyang/archive/2013/02/25/