LoginSignup
1
1

More than 5 years have passed since last update.

postScaleを使ってKiiCloudにアップロードするbitmapのサイズを半分にする方法

Posted at

KiiCloudのチュートリアルを編集して、アップロードするbitmapのサイズを半分にする方法。

PostActivity.java
//uriからファイルのパスを取得する。バージョンによって処理が違う。
//KiiCloudのチュートリアルから取り込んだ。汎用的に使えます。
    private String getFilePathByUri(Uri selectedFileUri) {
        //4.2以降の時
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
            // Workaround of retrieving file image through ContentResolver
            // for Android4.2 or later
            String filePath = null;
            FileOutputStream fos = null;
            try {
                //ビットマップの変換サイズを定義
                Matrix varMat = new Matrix();
                varMat.postScale(0.5F, 0.5F);
                //ビットマップを取得
                Bitmap bmp = MediaStore.Images.Media.getBitmap(
                        this.getContentResolver(), selectedFileUri);
                //ビットマップを定義したサイズに変換
                Bitmap bmp2 = Bitmap.createBitmap(
                        bmp, 0, 0,
                        bmp.getWidth(),
                        bmp.getHeight(),
                        varMat, true
                );
                //一時保存するディレクトリ。アプリに応じてappの部分を変更したほうが良い
                String cacheDir = Environment.getExternalStorageDirectory()
                        .getAbsolutePath() + File.separator + "app";
                //ディレクトリ作成
                File createDir = new File(cacheDir);
                if (!createDir.exists()) {
                    createDir.mkdir();
                }
                //一時ファイル名を作成。毎回上書き
                filePath = cacheDir + File.separator + "upload.jpg";
                File file = new File(filePath);
                //ビットマップをjpgに変換して一時的に保存する。
                fos = new FileOutputStream(file);
                bmp2.compress(Bitmap.CompressFormat.JPEG, 95, fos);
                fos.flush();
                fos.getFD().sync();
            } catch (Exception e) {
                filePath = null;
            } finally {//かならず最後に実行する処理
                if (fos != null) {
                    try {
                        //ファイルを閉じる
                        fos.close();
                    } catch (Exception e) {
                        // Nothing to do
                    }
                }
            }
            return filePath;
        } 

1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1