image

来源:互联网 发布:写代码的软件 编辑:程序博客网 时间:2024/05/16 11:17


package com.apicloud.UzImageUtil;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Base64;

import com.apicloud.UzImageUtil.LocalAlbums.GlobalScreenshot;
import com.apicloud.UzImageUtil.LocalAlbums.LocalAlbum;
import com.apicloud.UzImageUtil.LocalAlbums.common.ImageUtils;
import com.apicloud.UzImageUtil.LocalAlbums.common.LocalImageHelper;
import com.uzmap.pkg.uzcore.UZWebView;
import com.uzmap.pkg.uzcore.uzmodule.UZModule;
import com.uzmap.pkg.uzcore.uzmodule.UZModuleContext;

@SuppressLint("SimpleDateFormat")
public class UzImageUtil extends UZModule {

 // 裁剪图片
 private static final int CROP_REQUEST_CODE = 1305;
 
 private static final int CROP_REQUEST_CODE_BIG = 1306; //截取大图
 
 UZModuleContext photoModuleContext;
 UZModuleContext viewListModuleContext;

 private String picName = "CROPED_FACE_IMG_001.jpg";

 private ArrayList<String> retImages;
 private int quality = 30; // 压缩质量
 private int targetWidth = 600;
 private int targetHeight = 800;
 private int imgCount = 9;
 private boolean showCarams=false;
 private String  tipMsg = "";

 String pre_file = "file://";
 String pre_content = "content://";

 public UzImageUtil(UZWebView webView) {
  super(webView);
 }

 @SuppressWarnings({ "rawtypes", "unchecked", "unused" })
 public void jsmethod_getImgSize(final UZModuleContext moduleContext) {
  JSONArray imgUrls = moduleContext.optJSONArray("imageArr");
  List list = new ArrayList();
  if (imgUrls == null || imgUrls.length() < 0) {
   imageSizeCallBack(moduleContext, false, null, "imageArr is null");
   return;
  }
  try {
   for (int i = 0; i < imgUrls.length(); i++) {// 遍历JSONArray
    String srcPath = imgUrls.get(i).toString();
    if (srcPath != "" || srcPath != null) {
     srcPath = srcPath.replace("file:/", "");
    }
    List<Integer> list2 = new ArrayList<Integer>();
    BitmapFactory.Options op = new BitmapFactory.Options();
    op.inJustDecodeBounds = true;// 只是读图片的属性
    Bitmap bitmap = BitmapFactory.decodeFile(srcPath, op);
    list2.add(op.outWidth);
    list2.add(op.outHeight);
    list.add(list2);
   }
  } catch (Exception e) {
   imageSizeCallBack(moduleContext, false, null, e.getMessage());
   e.printStackTrace();
  }
  imageSizeCallBack(moduleContext, true, list, "success");
 }

 // 获取图片list
 public void jsmethod_getViewImgList(UZModuleContext moduleContext) {
  viewListModuleContext = moduleContext;
  quality = moduleContext.optInt("quality") > 0 ? moduleContext .optInt("quality") : quality;
  targetWidth = moduleContext.optInt("targetWidth") > 0 ? moduleContext .optInt("targetWidth") : targetWidth;
  targetHeight = moduleContext.optInt("targetHeight") > 0 ? moduleContext .optInt("targetHeight") : targetHeight;
  imgCount = moduleContext.optInt("imgCount") > 0 ? moduleContext .optInt("imgCount") : imgCount;
  showCarams = moduleContext.optBoolean("showCarams");
  tipMsg = (moduleContext.optString("msg") !=null && moduleContext.optString("msg").length() >0) ? moduleContext .optString("msg") : tipMsg;
  retImages = new ArrayList<String>();
  Intent intent = new Intent(mContext, LocalAlbum.class);
  intent.putExtra("imgCount", imgCount);
  intent.putExtra("tipMsg", tipMsg);
  startActivityForResult(intent, ImageUtils.REQUEST_CODE_GETIMAGE_BYCROP_LIST);
 }
 

 public void jsmethod_pictureTobase64WithLocalImage(UZModuleContext moduleContext) {
  try {
   String imagePath = moduleContext.optString("imagePath");
   if(imagePath.startsWith("file:")){
    imagePath = imagePath.replace("file:", "");
   }
   File f1 = new File(imagePath);
   if (!f1.exists()) { // 不存在,则直接编辑
    imageCallBack(moduleContext, "", false);
    return;
   }
   FileInputStream inputFile = new FileInputStream(f1);
   byte[] buffer = new byte[(int) f1.length()];
   inputFile.read(buffer);
   inputFile.close();
   String strImageBase64 = Base64.encodeToString(buffer, Base64.DEFAULT);
   imageCallBack(moduleContext, strImageBase64, true);
  } catch (Exception e) {
   imageCallBack(moduleContext, e.getMessage(), false);
  }

 }

 // 裁剪图片
 public void jsmethod_startPhotoZoom(UZModuleContext moduleContext) {
  photoModuleContext = moduleContext;
  // outputX outputY 是裁剪图片宽高
  Integer outputX = 100;
  Integer outputY = 100;
  // aspectX aspectY 是宽高的比例
  Integer aspectX = 1;
  Integer aspectY = 1;

  String srcFilePath = moduleContext.optString("filePath");
  outputX = moduleContext.optInt("outputX") > 0 ? moduleContext .optInt("outputX") : outputX;
  outputY = moduleContext.optInt("outputY") > 0 ? moduleContext .optInt("outputY") : outputY;
  aspectX = moduleContext.optInt("aspectX") > 0 ? moduleContext .optInt("aspectX") : aspectX;
  aspectY = moduleContext.optInt("aspectY") > 0 ? moduleContext .optInt("aspectY") : aspectY;
  picName = (moduleContext.optString("picName") != null && moduleContext.optString("picName").length()>0) ? moduleContext .optString("picName") : picName;

  if (srcFilePath == "" || srcFilePath == null) {
   getMsgCallBack(moduleContext, "not find img");
   return;
  }
  String fileDir = srcFilePath.replace("file:/", "");
  startPhotoZoom(Uri.fromFile(new File(fileDir)), outputX, outputY, aspectX, aspectY);
 }

 public void startPhotoZoom(Uri uri, Integer outputX, Integer outputY, Integer aspectX, Integer aspectY) {
  Intent intent = new Intent("com.android.camera.action.CROP");
  intent.setDataAndType(uri, "image/*");
  // 设置裁剪
  intent.putExtra("crop", "true");
  // aspectX aspectY 是宽高的比例
  intent.putExtra("aspectX", aspectX);
  intent.putExtra("aspectY", aspectY);
  // outputX outputY 是裁剪图片宽高
  intent.putExtra("outputX", outputX);
  intent.putExtra("outputY", outputY);
  intent.putExtra("return-data", true);
  startActivityForResult(intent, CROP_REQUEST_CODE);
  
 }
 
 // 裁剪图片
 Uri myImageUri = null;
 public void jsmethod_startPhotoZoomBig(UZModuleContext moduleContext) {
  photoModuleContext = moduleContext;
  // outputX outputY 是裁剪图片宽高
  Integer outputX = 300;
  Integer outputY = 300;
  // aspectX aspectY 是宽高的比例
  Integer aspectX = 2;
  Integer aspectY = 3;

  String srcFilePath = moduleContext.optString("filePath");
  quality = moduleContext.optInt("quality") > 0 ? moduleContext .optInt("quality") : quality;
  outputX = moduleContext.optInt("outputX") > 0 ? moduleContext .optInt("outputX") : outputX;
  outputY = moduleContext.optInt("outputY") > 0 ? moduleContext .optInt("outputY") : outputY;
  aspectX = moduleContext.optInt("aspectX") > 0 ? moduleContext .optInt("aspectX") : aspectX;
  aspectY = moduleContext.optInt("aspectY") > 0 ? moduleContext .optInt("aspectY") : aspectY;
  picName = (moduleContext.optString("picName") != null && moduleContext.optString("picName").length()>0) ? moduleContext .optString("picName") : "MyBigWall.jpg";

  if (srcFilePath == "" || srcFilePath == null) {
   getMsgCallBack(moduleContext, "not find img");
   return;
  }
  String fileDir = srcFilePath.replace("file:/", "");
  startPhotoZoomBig(Uri.fromFile(new File(fileDir)), outputX, outputY, aspectX, aspectY,srcFilePath);
 }
 
 @SuppressWarnings("unused")
 public void startPhotoZoomBig(Uri uri, Integer outputX, Integer outputY, Integer aspectX, Integer aspectY,String srcFilePath) {
  if(!srcFilePath.startsWith("file:/")){
   srcFilePath = "file://"+srcFilePath;
  }
  Uri oldImageUri =  Uri.parse(srcFilePath);
  String IMAGE_FILE_LOCATION = "file:///storage/sdcard1/DCIM/Camera/mytmp.jpg";//temp file
  if (Environment.getExternalStorageState().equals( Environment.MEDIA_MOUNTED)) {
   File file = new File(Environment .getExternalStorageDirectory().getAbsolutePath() + File.separator + picName);
   IMAGE_FILE_LOCATION = "file://"+Environment .getExternalStorageDirectory().getAbsolutePath() + File.separator + picName;
  }
  myImageUri = Uri.parse(IMAGE_FILE_LOCATION);//The Uri to store the big bitmap
  
  
  Intent intent = new Intent("com.android.camera.action.CROP");
  //intent.setType("image/*");
  intent.setDataAndType(oldImageUri, "image/*");
  intent.putExtra("crop", "true");
  intent.putExtra("aspectX", aspectX);
  intent.putExtra("aspectY", aspectY);
  intent.putExtra("outputX", outputX);
  intent.putExtra("outputY", outputY);
  intent.putExtra("scale", true);
  intent.putExtra("return-data", false);
  intent.putExtra(MediaStore.EXTRA_OUTPUT, myImageUri);
  intent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());
  intent.putExtra("noFaceDetection", true); // no face detection
  startActivityForResult(intent, CROP_REQUEST_CODE_BIG);

 }

 @Override
 public void onActivityResult(int requestCode, int resultCode, Intent data) {
  super.onActivityResult(requestCode, resultCode, data);
  switch (requestCode) {
  case CROP_REQUEST_CODE: // 图片缩放完成后
   if (data != null) {
    getImageToView(data);
   }
   break;
  case CROP_REQUEST_CODE_BIG: // 图片缩放完成后
   if(myImageUri != null){
    Bitmap screenShotBitmap = decodeUriAsBitmap(myImageUri);//decode bitmap
    if (Environment.getExternalStorageState().equals( Environment.MEDIA_MOUNTED)) {
     File file = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator + picName);
     //Log.e("", "leiricong === "+Environment .getExternalStorageDirectory().getAbsolutePath() + File.separator + "00test1.jpg");
     try {
      FileOutputStream outputStream = new FileOutputStream( file);
      screenShotBitmap.compress(Bitmap.CompressFormat.PNG, quality, outputStream);
      // 根据自己需求,如果外边对bitmp还有别的需求就不要recycle的
      screenShotBitmap.recycle();
      outputStream.close();
      getMsgCallBack(photoModuleContext, Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator + picName);
     } catch (Exception e) {
      e.printStackTrace();
     }
    }else{
     
    }
   }
   break;
  case ImageUtils.REQUEST_CODE_GETIMAGE_BYCROP_LIST:
   if (LocalImageHelper.getInstance().isResultOk()) {
    LocalImageHelper.getInstance().setResultOk(false);
    // 获取选中的图片
    List<LocalImageHelper.LocalFile> files = LocalImageHelper .getInstance().getCheckedItems();
    for (int i = 0; i < files.size(); i++) {
     String oriPath = files.get(i).getOriginalUri();
     if (oriPath.startsWith(pre_file)) {
      oriPath = files.get(i).getOriginalUri() .replace("file:/", "");
          try {
           if(showCarams){
            MediaStore.Images.Media.insertImage(mContext.getContentResolver(), oriPath, "", null);
           }
      } catch (FileNotFoundException e) {
       e.printStackTrace();
      }
     } else if (oriPath.startsWith(pre_content)) {
      oriPath = ImageUtils.getAbsoluteImagePath(mContext, Uri.parse(oriPath));
     }
     copyPicToTarget(oriPath);
    }
    files.clear();
    LocalImageHelper.getInstance().getCheckedItems().clear();
    imageListCallBack(viewListModuleContext, true, retImages, "");
   }
  }
 }
 private Bitmap decodeUriAsBitmap(Uri uri){
  Bitmap bitmap = null;
  try {
   bitmap = BitmapFactory.decodeStream(mContext.getContentResolver().openInputStream(uri));
  } catch (FileNotFoundException e) {
   e.printStackTrace();
   return null;
  }
  return bitmap;
 }
 public void copyPicToTarget(String oldPath) {
  String fileDirTmp = (viewListModuleContext.optString("filePath")!= null && viewListModuleContext.optString("filePath").length()>0) ? viewListModuleContext .optString("filePath") : "file:///storage/sdcard0/UZMap/LRCCC/";
  // "file:///storage/sdcard1/UZMap/A6913863031949/SJB/SJB"
  
  String targetPath = fileDirTmp.replace("file:/", "");
  try {
   File newdir = new File(targetPath);
   if (!newdir.exists() && !newdir.isDirectory()) {
    newdir.mkdirs();
   }
   File oldfile = new File(oldPath);
   if (oldfile.exists()) { // 文件存在时
    UUID uuid = UUID.randomUUID();
    String newPath = "";
    String timeStamp = new SimpleDateFormat("yyyyMMddHHmmss") .format(new Date());
    if (uuid == null) {
     newPath = newdir + "/" + timeStamp+(new Date().getTime()) + ".jpg"; // fileOutPut  将文件copy到那个目录下面
    } else {
     newPath = newdir + "/" + timeStamp+ uuid.toString().replaceAll("-", "") + ".jpg"; // fileOutPut  将文件copy到那个目录下面
    }
    Bitmap bmp = ImageUtils.decodeBitmap(targetWidth, targetHeight, oldPath);
    File file = null;
    file = new File(newPath);
    file.delete();
    ByteArrayOutputStream stream = new ByteArrayOutputStream();
    bmp.compress(CompressFormat.JPEG, quality, stream);
    FileOutputStream os = new FileOutputStream(file);
    os.write(stream.toByteArray());
    os.close();
    bmp = BitmapFactory.decodeFile(newPath);
    retImages.add(newPath);
   }
  } catch (Exception e) {
   System.out.println("复制单个文件操作出错");
   e.printStackTrace();
  }
 }

 // 图片裁剪之后显示图片
 private void getImageToView(Intent data) {
  Bundle extras = data.getExtras();
  
  if (extras != null) {
   Bitmap photo = extras.getParcelable("data");
   String SAVE_IMG_PATH = mContext.getFilesDir().toString();
   File file_phto = new File(SAVE_IMG_PATH, picName);
   if (file_phto.exists()) {
    file_phto.delete();
   }

   OutputStream stream = null;
   try {
    stream = new FileOutputStream(file_phto);
    photo.compress(Bitmap.CompressFormat.JPEG, 80, stream);
    try {
     stream.close();
     getMsgCallBack(photoModuleContext, file_phto.getAbsolutePath());
     photoModuleContext = null;
    } catch (IOException e) {
     e.printStackTrace();
    }
   } catch (Exception e) {
    getMsgCallBack(photoModuleContext, e.getMessage());
    e.printStackTrace();
   }

  }else{
   getMsgCallBack(photoModuleContext, data.getDataString());
  }
 }

 @SuppressWarnings("rawtypes")
 private void imageSizeCallBack(UZModuleContext moduleContext, boolean status, List listImageSizes, String msg) {
  JSONObject ret = new JSONObject();
  try {
   ret.put("status", status);
   if (status) {
    ret.put("imageSize", listImageSizes);
   } else {
    ret.put("msg", msg);
   }
   moduleContext.success(ret, false);
  } catch (JSONException e) {
   e.printStackTrace();
  }
 }

 private void getMsgCallBack(UZModuleContext moduleContext, String msg) {
  JSONObject ret = new JSONObject();
  try {
   ret.put("msg", msg);
   moduleContext.success(ret, false);
  } catch (JSONException e) {
   e.printStackTrace();
  }
 }

 private void imageListCallBack(UZModuleContext moduleContext, boolean status, ArrayList<String> listImageSizes, String msg) {
  JSONObject ret = new JSONObject();
  JSONArray listImageSizeArray = new JSONArray();
  try {
   ret.put("status", status);
   if (status) {
    if(listImageSizes.size()>0){
     for(String str : listImageSizes){
      listImageSizeArray.put(str);
     }
    }
    ret.put("imagePath", listImageSizeArray);
   } else {
    ret.put("msg", msg);
   }
   moduleContext.success(ret, false);
  } catch (JSONException e) {
   e.printStackTrace();
  }
 }

 private void imageCallBack(UZModuleContext moduleContext, String content, boolean status) {
  JSONObject ret = new JSONObject();
  try {
   ret.put("msg", content);
   ret.put("status", status);
   moduleContext.success(ret, false);
  } catch (JSONException e) {
   e.printStackTrace();
  }
 }
}

0 0
原创粉丝点击