com.pixby.texo.images.ImageUtil.java Source code

Java tutorial

Introduction

Here is the source code for com.pixby.texo.images.ImageUtil.java

Source

package com.pixby.texo.images;

/*
 * Copyright (c) 2016 David Allen
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */

import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Rect;
import android.os.Environment;
import android.provider.OpenableColumns;
import android.support.v4.app.ActivityCompat;
import android.util.Log;

import com.pixby.texo.R;

import java.io.File;
import java.util.Locale;

public class ImageUtil {

    private static final String TAG = ImageUtil.class.getSimpleName();

    public static final int TEMP_FOLDER = 1;
    public static final int APP_FOLDER = 2;
    public static final int SIZE_EXPORT = 1;
    public static final int SIZE_SHARE = 2;

    public static final int PICK_IMAGE_REQUEST = 1;

    public static final int REQUEST_EXTERNAL_STORAGE = 1;
    private static final String[] PERMISSIONS_STORAGE = { Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.WRITE_EXTERNAL_STORAGE };

    /**
     * Checks if the app has permission to write to device storage
     * If the app does not have permission then the user will be prompted to grant permissions
     */
    public static boolean verifyStoragePermissions(Activity activity) {
        // Check if we have write permission
        int permission = ActivityCompat.checkSelfPermission(activity, Manifest.permission.WRITE_EXTERNAL_STORAGE);

        if (permission != PackageManager.PERMISSION_GRANTED) {
            // We don't have permission so prompt the user
            ActivityCompat.requestPermissions(activity, PERMISSIONS_STORAGE, REQUEST_EXTERNAL_STORAGE);
            return false;
        }
        return true;
    }

    public static Rect calcTargetSize(int width, int height, int outputSizeFlag) {
        float scale = getSizeFactor(outputSizeFlag);
        int w = (int) (width * scale);
        int h = (int) (height * scale);
        return new Rect(0, 0, w, h);
    }

    private static float getSizeFactor(int targetSizeFlag) {
        float factor;
        if (targetSizeFlag == SIZE_SHARE) {
            factor = 0.5f;
        } else {
            factor = 1.f;
        }
        return factor;
    }

    public static String getOutputFolder(Context context, String fileName, int folderType) {
        String path = getOutputFolder(context, folderType);
        String name = getOutputName(fileName);
        return path + File.separator + name;
    }

    private static String getOutputName(String fileName) {
        String rootName = getFileNameWithoutExtension(fileName);
        return String.format(Locale.getDefault(), "%s-%d.jpg", rootName, System.currentTimeMillis());
    }

    private static String getFileNameWithoutExtension(String name) {
        int pos = name.lastIndexOf('.');
        if (pos > 0 && pos < (name.length() - 1)) {
            return name.substring(0, pos);
        }
        return name;
    }

    private static String getOutputFolder(Context context, int folderType) {
        if (folderType == TEMP_FOLDER) {
            return getAppTempPath(context);
        } else {
            return getAppStoragePath(context.getString(R.string.app_name));
        }
    }

    // Get the directory for the user's public pictures directory.
    private static String getAppTempPath(Context context) {
        return context.getExternalCacheDir().getPath();
    }

    // Get the folder for the user's public pictures + app name
    private static String getAppStoragePath(String albumName) {
        File storageDir = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),
                albumName);

        if (!storageDir.exists()) {
            if (!storageDir.mkdirs()) {
                Log.e(TAG, "getAppStoragePath mkdirs failed: " + storageDir.getAbsolutePath());
            }
        }
        return storageDir.getPath();
    }

    public static String getFileNameFromCursor(Cursor cursor) {
        int nameIndex = cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME);
        cursor.moveToFirst();
        return cursor.getString(nameIndex);
    }

    public static String getTimestamp() {
        Long tsLong = System.currentTimeMillis() / 1000;
        return tsLong.toString();
    }

    public static void getImageFromGallery(Activity activity) {
        Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
        intent.setType("image/*");
        activity.startActivityForResult(Intent.createChooser(intent, "Choose Photo"), ImageUtil.PICK_IMAGE_REQUEST);
    }

    public static void deleteCachedImage(String path) {
        if (path != null && !path.isEmpty()) {
            File f = new File(path);
            if (f.exists()) {
                if (!f.delete()) {
                    Log.e(TAG, String.format("Delete failed for cached share image %s", f.getAbsolutePath()));
                }
            }
        }
    }
}