Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

//package com.java2s;
//License from project: Apache License 

import android.content.ContentResolver;
import android.content.Context;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;

import android.net.Uri;

import java.io.ByteArrayOutputStream;

import java.io.FileNotFoundException;

import java.io.InputStream;

public class Main {
    /**
     * Convert an image to a byte array
     * @param uri
     * @param context
     * @return
     */
    public static byte[] convertImageToByte(Uri uri, Context context) {
        byte[] data = null;
        try {
            ContentResolver cr = context.getContentResolver();
            InputStream inputStream = cr.openInputStream(uri);
            Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            bitmap.compress(Bitmap.CompressFormat.PNG, 100, baos);
            data = baos.toByteArray();
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (Exception e2) {
                }
            }
            if (baos != null) {
                try {
                    baos.close();
                } catch (Exception e2) {
                }
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        return data;
    }
}