그림 관련 도구 방법
Base64 방식으로 업로드
//       bitmap   String   
public String file2String(String path) {
    File file = new File(path);
    String string = null;
    FileInputStream inputFile = null;
    try {
        inputFile = new FileInputStream(file);
        byte[] buffer = new byte[(int) file.length()];
        inputFile.read(buffer);
        inputFile.close();
        string = Base64.encodeToString(buffer, Base64.DEFAULT);
    } catch (IOException e) {
        e.printStackTrace();
    }
    return string;
}
public String bitmap2String(String path) {
    Bitmap bitmap = BitmapFactory.decodeFile(path);
    ByteArrayOutputStream bos=new ByteArrayOutputStream();
    if (bitmap != null) {
        bitmap.compress(Bitmap.CompressFormat.JPEG, 40, bos);
    }
    byte[] bytes=bos.toByteArray();
    String string = Base64.encodeToString(bytes, Base64.DEFAULT);
    return string;
}
그림uri 가져오기
상대 경로(/storage/emulated/0/Pictures/IMG 20171108 180509.jpg)를 기준으로 URI로 전환:content://media/external/images/media
private Uri getImageContentUri(String filePath) {
    if (TextUtils.isEmpty(filePath)) {
        return null;
    }
    Cursor cursor = App.getInstance().getContentResolver().query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
            new String[]{MediaStore.Images.Media._ID}, MediaStore.Images.Media.DATA + "=? ",
            new String[]{filePath}, null);
    if (cursor != null && cursor.moveToFirst()) {
        int id = cursor.getInt(cursor.getColumnIndex(MediaStore.MediaColumns._ID));
        Uri baseUri = Uri.parse("content://media/external/images/media");
        cursor.close();
        return Uri.withAppendedPath(baseUri, "" + id);
    } else {
        if (!TextUtils.isEmpty(filePath)) {
            ContentValues values = new ContentValues();
            values.put(MediaStore.Images.Media.DATA, filePath);
            return App.getInstance().getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
        } else {
            return null;
        }
    }
}
카메라를 들어 올리면서 사진을 찍습니다.
//         
private void takePhoto() {
    String SDState = Environment.getExternalStorageState();
    if (SDState.equals(Environment.MEDIA_MOUNTED)) {
        tempFile = getPhotoFile();
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        //                 
        intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(tempFile));
        startActivityForResult(intent, REQUEST_CODE_CAMERA);
    } else {
        Toast.makeText(this, "no SD card!", Toast.LENGTH_LONG).show();
    }
}
//          
private File getPhotoFile() {
//        String path = 
Environment.getExternalStorageDirectory().getAbsolutePath();
    File file = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
    Date date = new Date(System.currentTimeMillis());
    SimpleDateFormat dateFormat = new SimpleDateFormat("'IMG'_yyyyMMdd_HHmmss");
    String format = dateFormat.format(date);
    return new File(file.getPath(), format + ".jpg");
}
앨범 열기를 통해 그림 선택
private void pickPhoto() {
//        Intent intent = new Intent(Intent.ACTION_PICK, null);
//        intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
    Intent intent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
    startActivityForResult(intent, REQUEST_CODE_PHOTO);
}
그림 압축 방법
품질 압축 방법
/**
 *       
 *
 * @param image
 * @return
 */
private Bitmap compressImage(Bitmap image) {
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    image.compress(Bitmap.CompressFormat.JPEG, 100, baos);//       ,  100     ,          baos 
    int options = 100;
    while (baos.toByteArray().length / 1024 > 100) { //                100kb,      
        baos.reset();//   baos   baos
        image.compress(Bitmap.CompressFormat.JPEG, options, baos);//     options%,          baos 
        options -= 10;//      10
    }
    ByteArrayInputStream isBm = new ByteArrayInputStream(baos.toByteArray());//        baos   ByteArrayInputStream 
    return BitmapFactory.decodeStream(isBm, null, null);
}
//======================================
/**
 *       :(  compress   )
 * 
 * 
 *      bitmap       maxSize,     
 *
 * @param bitmap        
 * @param maxSize       ,  kb
 */
private Bitmap compress(Bitmap bitmap, double maxSize) {
    //  bitmap     ,    bitmap   (           )
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    //   、  、   
    bitmap.compress(Bitmap.CompressFormat.PNG, 70, baos);
    byte[] b = baos.toByteArray();
    //      KB
    double mid = b.length / 1024;
    //   bitmap              
    double i = mid / maxSize;
    //   bitmap                             
    if (i > 1) {
        //                              
        // (      ,                )
        // scale      scale  
        bitmap = scale(bitmap, bitmap.getWidth() / Math.sqrt(i),
                bitmap.getHeight() / Math.sqrt(i));
    }
    return bitmap;
}
그림 크기 조정 방법, 지정한 길이와 너비로 크기 조정
/**
 *        
 *
 * @param src       :     
 * @param newWidth  :     
 * @param newHeight :     
 */
private Bitmap scale(Bitmap src, double newWidth, double newHeight) {
    //   src   
    float width = src.getWidth();
    float height = src.getHeight();
    //     matrix  
    Matrix matrix = new Matrix();
    //       
    float scaleWidth = ((float) newWidth) / width;
    float scaleHeight = ((float) newHeight) / height;
    //     
    matrix.postScale(scaleWidth, scaleHeight);
    //         
    return Bitmap.createBitmap(src, 0, 0, (int) width, (int) height,
            matrix, true);
}
비례에 따라 압축하다
/**
 *            
 *
 * @param srcPath (           )
 * @return
 */
private Bitmap getOptimizedImage(String srcPath) {
    // Log.d(TAG, "getOptimizedImage --> isInMainThread " + Utils.isInMainThread());
    BitmapFactory.Options newOpts = new BitmapFactory.Options();
    //       ,   options.inJustDecodeBounds   true 
    newOpts.inJustDecodeBounds = true;
    Bitmap bitmap = BitmapFactory.decodeFile(srcPath, newOpts);//     bm  
    newOpts.inJustDecodeBounds = false;
    int w = newOpts.outWidth;
    int h = newOpts.outHeight;
    //           800*480   ,          
    float hh = 800;//        800f
    float ww = 480;//        480f
    //    。         ,                  
    int be = 1;// 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;//       
    //       ,       options.inJustDecodeBounds   false 
    bitmap = BitmapFactory.decodeFile(srcPath, newOpts);
    return compress(bitmap, 500L);//                
}
참고: 이미지 압축을 할 때는 가능한 하위 스레드에 압축을 적용하십시오. 압축 프로세스가 시간이 많이 걸리기 때문에 ANR을 던질 수 있습니다.
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
다양한 언어의 JSONJSON은 Javascript 표기법을 사용하여 데이터 구조를 레이아웃하는 데이터 형식입니다. 그러나 Javascript가 코드에서 이러한 구조를 나타낼 수 있는 유일한 언어는 아닙니다. 저는 일반적으로 '객체'{}...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.