Gradles
//amazon s3compile 'com.amazonaws:aws-android-sdk-core:2.2.+'
compile 'com.amazonaws:aws-android-sdk-s3:2.2.+'
Declare in manefiest file
<!--AMAZON S3--><service android:name="com.amazonaws.mobileconnectors.s3.transferutility.TransferService" android:enabled="true" />
AmazonUtils.java
import android.content.Context; import android.net.Uri; import com.amazonaws.auth.CognitoCachingCredentialsProvider; import com.amazonaws.mobileconnectors.s3.transferutility.TransferObserver; import com.amazonaws.mobileconnectors.s3.transferutility.TransferUtility; import com.amazonaws.regions.Regions; import com.amazonaws.services.s3.AmazonS3Client; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.util.Map; import java.util.UUID; /* * Handles basic helper functions used throughout the app. */public class AmazonUtil { // We only need one instance of the clients and credentials provider private static AmazonS3Client sS3Client; private static CognitoCachingCredentialsProvider sCredProvider; private static TransferUtility sTransferUtility; /** * Gets an instance of CognitoCachingCredentialsProvider which is * constructed using the given Context. * * @param context An Context instance. * @return A default credential provider. */ private static CognitoCachingCredentialsProvider getCredProvider(Context context) { if (sCredProvider == null) { sCredProvider = new CognitoCachingCredentialsProvider( context.getApplicationContext(), S3Constants.COGNITO_POOL_ID, Regions.EU_WEST_1); } return sCredProvider; } /** * Gets an instance of a S3 client which is constructed using the given * Context. * * @param context An Context instance. * @return A default S3 client. */ public static AmazonS3Client getS3Client(Context context) { if (sS3Client == null) { sS3Client = new AmazonS3Client(getCredProvider(context.getApplicationContext())); } return sS3Client; } /** * Gets an instance of the TransferUtility which is constructed using the * given Context * * @param context * @return a TransferUtility instance */ public static TransferUtility getTransferUtility(Context context) { if (sTransferUtility == null) { sTransferUtility = new TransferUtility(getS3Client(context.getApplicationContext()), context.getApplicationContext()); } return sTransferUtility; } /** * Converts number of bytes into proper scale. * * @param bytes number of bytes to be converted. * @return A string that represents the bytes in a proper scale. */ public static String getBytesString(long bytes) { String[] quantifiers = new String[]{ "KB", "MB", "GB", "TB" }; double speedNum = bytes; for (int i = 0; ; i++) { if (i >= quantifiers.length) { return ""; } speedNum /= 1024; if (speedNum < 512) { return String.format("%.2f", speedNum) + " " + quantifiers[i]; } } } /** * Copies the data from the passed in Uri, to a new file for use with the * Transfer Service * * @param context * @param uri * @return * @throws IOException */ public static File copyContentUriToFile(Context context, Uri uri) throws IOException { InputStream is = context.getContentResolver().openInputStream(uri); File copiedData = new File(context.getDir("SampleImagesDir", Context.MODE_PRIVATE), UUID .randomUUID().toString()); copiedData.createNewFile(); FileOutputStream fos = new FileOutputStream(copiedData); byte[] buf = new byte[2046]; int read = -1; while ((read = is.read(buf)) != -1) { fos.write(buf, 0, read); } fos.flush(); fos.close(); return copiedData; } /* * Fills in the map with information in the observer so that it can be used * with a SimpleAdapter to populate the UI */ public static void fillMap(Map<String, Object> map, TransferObserver observer, boolean isChecked) { int progress = (int) ((double) observer.getBytesTransferred() * 100 / observer .getBytesTotal()); map.put("id", observer.getId()); map.put("checked", isChecked); map.put("fileName", observer.getAbsoluteFilePath()); map.put("progress", progress); map.put("bytes", getBytesString(observer.getBytesTransferred()) + "/" + getBytesString(observer.getBytesTotal())); map.put("state", observer.getState()); map.put("percentage", progress + "%"); }S3Constants.javapublic class S3Constants { public static String AMAZON_BASE_URL = "https://backetname.s3.amazonaws.com/"; public static final String BUCKET_PARENT = "backetname"; public static final String PATIENT_FOLDER = "patient/"; public static final int PROFILE_HEIGHT_WIDTH = 720; public static final String S3_ACCESS_KEY = "AKIAJCX3F5ZLJZ7EZQEA"; public static final String S3_SECRET_KEY = "=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"; //OLD// public static final String AWS_ACCOUNT_ID = "294944445604";// public static final String COGNITO_POOL_ID = "us-east-1:74818665-5ac8-47de-b996-ab88dd4dcf93";// public static final String COGNITO_ROLE_AUTH = "arn:aws:iam::294944445604:role/Cognito_HuudleAppUnauth_DefaultRole";// public static final String COGNITO_ROLE_UNAUTH = "arn:aws:iam::294944445604:role/Cognito_HuudleAppAuth_DefaultRole"; // old server keys// Access Key ID:AKIAI7S3BZPEE4WI343Q// Secret Access Key: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 //INTIALIZATION OF AWS VARIABLES. public static final String AWS_ACCOUNT_ID = "602898837969"; // public static final String COGNITO_POOL_ID = "us-east-1:ed3d7f5a-1e1a-4037-8a0a-23f6382af3f0"; public static final String COGNITO_POOL_ID = "eu-west-1:b7c03860-e3c0-42a0-8164-6f45b403dc17"; // public static final String AWS_ACCOUNT_ID = "110289883796";// public static final String COGNITO_POOL_ID = "us-east-1:110289883796-41s00-4b85-ba8b-9e367e862d7d";// public static final String COGNITO_ROLE_AUTH = "arn:aws:iam::110289883796:role/Cognito_TestAuth_Role";// public static final String COGNITO_ROLE_UNAUTH = "arn:aws:iam::110289883796:role/Cognito_TestUnauth_Role"; // Cognito_AndromakUnauth_Role }Code to upload Image on S3 Serverprivate ImageLoadingUtils imageLoadingUtils;MediaHelper mediaHelpers;// The TransferUtility is the primary class for managing transfer to S3private TransferUtility transferUtility; // A List of all transfersprivate TransferObserver observer; private ImageLoadingUtils imageLoadingUtils;// Initializes TransferUtility, always do this before using it.transferUtility = AmazonUtil.getTransferUtility(this);imageLoadingUtils = new ImageLoadingUtils(this);mediaHelpers = new MediaHelper(this);/** Begins to upload the file specified by the file path.*/ private void beginUpload(String filePath) { if (!isProgressDialogVisible()) { showProgressDialog(EditProfileActivity.this); } if (filePath == null) { Toast.makeText(this, "Could not find the filepath of the selected file", Toast.LENGTH_LONG).show(); return; } File file = new File(filePath); observer = transferUtility.upload(S3Constants.BUCKET_PARENT, folderName + PROFILE_PIC, file); Log.e(TAG, "beginUpload: url=" + S3Constants.AMAZON_BASE_URL + folderName + PROFILE_PIC); strProfileUrl = S3Constants.AMAZON_BASE_URL + S3Constants.PATIENT_FOLDER + userId + "/" + PROFILE_PIC; /* * Note that usually we set the transfer successListener after initializing the * transfer. However it isn't required in this sample app. The flow is * click upload button -> start an activity for image selection * startActivityForResult -> onActivityResult -> beginUpload -> onResume * -> set listeners to in progress transfers. */ observer.setTransferListener(new UploadListener()); }/* * A TransferListener class that can listen to a upload task and be notified * when the status changes. */ private class UploadListener implements TransferListener { // Simply updates the UI list when notified. @Override public void onError(int id, Exception e) { Log.e(TAG, "Error during upload: " + id, e); // updateList(); } @Override public void onProgressChanged(int id, long bytesCurrent, long bytesTotal) { Log.d(TAG, String.format("onProgressChanged: %d, total: %d, current: %d", id, bytesTotal, bytesCurrent)); // updateList(); } @Override public void onStateChanged(int id, TransferState newState) { Log.d(TAG, "onStateChanged: " + id + ", " + newState); if (newState.equals(TransferState.COMPLETED)) { /**call request**/ editProfileRequest(detailModel); Log.e(TAG, "onStateChanged: COMPLETED"); } else if (newState.equals(TransferState.FAILED)) { hideProgressDialog(); Log.e(TAG, "onStateChanged: FAILED"); } else if (newState.equals(TransferState.CANCELED)) { hideProgressDialog(); Log.e(TAG, "onStateChanged: CANCELED"); } } }/** * IMAGE COMPRESS PROCESS. */ class ImageCompressionAsyncTask extends AsyncTask<String, Void, String> { String path; public ImageCompressionAsyncTask(String path) { this.path = path; } @Override protected String doInBackground(String... params) { /** * recalculate image height width to create thumb image **/// ArrayList<Float> imageHeightWidth = Utility.getImageHeightWidth(mImageUri);// String filePath = Utility.compressImage(params[0], imageLoadingUtils// , mediaHelper.IMAGE_STORAGE_DIR_PROFILE, new File(mOutputFilePath).getName(), AndromakConstant.CREATE_POST_THUMB_HEIGHT_WIDTH, AndromakConstant.CREATE_POST_THUMB_HEIGHT_WIDTH); String filePath; filePath = Utils.compressImage(path, imageLoadingUtils, mediaHelpers.IMAGE_STORAGE_DIR_PROFILE, new File(strProfilePath).getName(), S3Constants.PROFILE_HEIGHT_WIDTH, S3Constants.PROFILE_HEIGHT_WIDTH); /**delete existing file before uploading new one**/// new deleteFileThread("").start(); return filePath; } @Override protected void onPostExecute(String result) { super.onPostExecute(result); Log.e(TAG, "onPostExecute: final file path=" + result); /***upload thumb on s3 server**/ beginUpload(result); } }MediaHelper.java/** * Media Helper : Helps developer to take picture from gallery, camera, vide from gallery and load them in image view If it is video thumbnail is shown on it. * * @author Pankaj Sharma */public class MediaHelper { private static final String TAG = "-MediaHelper-"; public int current_code_to_send = 100; public static final String IMAGE_FILE_EXT = ".jpg"; public static final String VIDEO_FILE_EXT = ".mp4"; public static final String IMAGE_STORAGE_DIR = Environment.getExternalStorageDirectory() + File.separator + Constants.PREF_NAME + File.separator + "Images"; public static final String VIDEO_STORAGE_DIR = Environment.getExternalStorageDirectory().getPath() + File.separator + "MediaHelper" + File.separator + "VIDEO"; public static final String IMAGE_STORAGE_DIR_PROFILE = Environment.getExternalStorageDirectory() + File.separator + Constants.PREF_NAME + File.separator + "Profile"; private HashMap<Integer, MediaCallback> mediaHolderList; public enum Media { IMAGE, VIDEO } private Activity mActivity; private Fragment mFragment; public MediaHelper(Activity activity) { // TODO Auto-generated constructor stub mActivity = activity; mediaHolderList = new HashMap<Integer, MediaCallback>(); File file = new File(IMAGE_STORAGE_DIR); if (!file.exists()) file.mkdirs(); } public MediaHelper(Fragment fragment) { // TODO Auto-generated constructor stub mFragment = fragment; mediaHolderList = new HashMap<Integer, MediaCallback>(); File file = new File(IMAGE_STORAGE_DIR); if (!file.exists()) file.mkdirs(); } private File getNewFile(Media type) { try { File rootDir = new File(type == Media.IMAGE ? IMAGE_STORAGE_DIR : VIDEO_STORAGE_DIR); if (!rootDir.exists()) { rootDir.mkdir(); } File file = new File(rootDir + File.separator + Constants.PREF_NAME + System.currentTimeMillis() + (type == Media.IMAGE ? IMAGE_FILE_EXT : VIDEO_FILE_EXT)); if (file.exists()) { file.delete(); } if (!file.exists()) { file.createNewFile(); } return file; } catch (Exception e) { e.printStackTrace(); } return null; } public File camera(int RequestCode) { File file = getNewFile(Media.IMAGE); Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); try { Uri mImageCaptureUri = null; String state = Environment.getExternalStorageState(); if (Environment.MEDIA_MOUNTED.equals(state)) { mImageCaptureUri = Uri.fromFile(file); } else { } intent.putExtra(android.provider.MediaStore.EXTRA_OUTPUT, mImageCaptureUri); intent.putExtra("return-data", true); mActivity.startActivityForResult(intent, RequestCode); } catch (ActivityNotFoundException e) { Log.e(TAG, "camera:cannot take picture ", e); } return file; } /*** * for new crop lib * * @param RequestCode * @return */ public File captureCamera(int RequestCode) { File file = getNewFile(Media.IMAGE); Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); try { intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(file)); mActivity.startActivityForResult(intent, RequestCode); } catch (ActivityNotFoundException e) { Log.e(TAG, "camera:cannot take picture ", e); } return file; } }MediaCallback.javapublic abstract class MediaCallback { public abstract void onResult(boolean status, File file, Media mediaType, Object object); public Object object; public File file; public Media mediaType; public Bitmap bitmap, thumbnailBitmap; /** * Called to show original image * * @param imageView */ public void showInImageView(ImageView imageView) { if (file.exists() && mediaType == Media.IMAGE) { if (bitmap == null) bitmap = createBitmapFromFile(file); imageView.setImageBitmap(bitmap); } else if (file.exists() && mediaType == Media.VIDEO) { showThumbnailInImageView(imageView); } } public Bitmap createBitmapFromFile(File file) { try { BitmapFactory.Options options = new BitmapFactory.Options(); options.inPreferredConfig = Bitmap.Config.ARGB_8888; options.inSampleSize = 2; Bitmap bm = BitmapFactory.decodeFile(file.getPath(), options); return bm; } catch (Exception e) { return null; } } /** * Called to show thumbnail image * * @param imageView */ public void showThumbnailInImageView(ImageView imageView) { if (file.exists() && mediaType == Media.IMAGE) { imageView.setImageBitmap(getThumbnailBitmap()); } else if (file.exists() && mediaType == Media.VIDEO) { imageView.setImageBitmap(getThumbnailBitmap()); } } public Bitmap getThumbnailBitmap() { if (thumbnailBitmap == null) { if (file.exists() && mediaType == Media.IMAGE) { if (bitmap == null) bitmap = BitmapFactory.decodeFile(file.getAbsolutePath()); int[] size = getThumbnailWidthHeight(); thumbnailBitmap = ThumbnailUtils.extractThumbnail(bitmap, size[0], size[1]); } else if (file.exists() && mediaType == Media.VIDEO) { thumbnailBitmap = ThumbnailUtils.createVideoThumbnail(file.getPath(), MediaStore.Video.Thumbnails.MICRO_KIND); if (thumbnailBitmap == null) { thumbnailBitmap = createThumbnailAtTime(file.getPath(), 150); } if (thumbnailBitmap == null) { onMessageCallback("Cannot generate thumbnail", null); } } } return thumbnailBitmap; } private Bitmap createThumbnailAtTime(String filePath, int timeInSeconds) { try { MediaMetadataRetriever mMMR = new MediaMetadataRetriever(); mMMR.setDataSource(filePath); // api clinicTime unit is microseconds return mMMR.getFrameAtTime(timeInSeconds * 1000000, MediaMetadataRetriever.OPTION_CLOSEST_SYNC); } catch (Exception e) { e.printStackTrace(); onMessageCallback(e.getMessage(), e); } return null; } public int[] getThumbnailWidthHeight() { return new int[]{512, 384}; } public void onMessageCallback(String message, Exception exception) { } }ImageLoadingUtils.javapublic class ImageLoadingUtils { private Context context; public Bitmap icon; public ImageLoadingUtils(Context context){ this.context = context; icon = BitmapFactory.decodeResource(context.getResources(), R.mipmap.ic_launcher); } public int convertDipToPixels(float dips){ Resources r = context.getResources(); return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dips, r.getDisplayMetrics()); } public int calculateInSampleSize(BitmapFactory.Options options, int reqWidth, int reqHeight) { final int height = options.outHeight; final int width = options.outWidth; int inSampleSize = 1; if (height > reqHeight || width > reqWidth) { final int heightRatio = Math.round((float) height / (float) reqHeight); final int widthRatio = Math.round((float) width / (float) reqWidth); inSampleSize = heightRatio < widthRatio ? heightRatio : widthRatio; } final float totalPixels = width * height; final float totalReqPixelsCap = reqWidth * reqHeight * 2; while (totalPixels / (inSampleSize * inSampleSize) > totalReqPixelsCap) { inSampleSize++; } return inSampleSize; } public Bitmap decodeBitmapFromPath(String filePath){ Bitmap scaledBitmap = null; BitmapFactory.Options options = new BitmapFactory.Options(); options.inJustDecodeBounds = true; scaledBitmap = BitmapFactory.decodeFile(filePath,options); options.inSampleSize = calculateInSampleSize(options, convertDipToPixels(150), convertDipToPixels(200)); options.inDither = false; options.inPurgeable = true; options.inInputShareable = true; options.inJustDecodeBounds = false; scaledBitmap = BitmapFactory.decodeFile(filePath, options); return scaledBitmap; } }CompressImage.javva/** * compress image * * @param imageUri * @param imageLoadingUtils * @param folderName * @param imagePath * @return */ public static String compressImage(String imageUri, ImageLoadingUtils imageLoadingUtils , String folderName, String imagePath, float height, float width) { // String filePath = getRealPathFromURI(imageUri); Bitmap scaledBitmap = null; BitmapFactory.Options options = new BitmapFactory.Options(); options.inJustDecodeBounds = true; Bitmap bmp = BitmapFactory.decodeFile(imageUri, options); int actualHeight = options.outHeight; int actualWidth = options.outWidth; /* float maxHeight = 1080.0f; float maxWidth = 1080.0f;*/ float maxHeight = height; float maxWidth = width; float imgRatio = (float) actualWidth / actualHeight; float maxRatio = maxWidth / maxHeight; if (actualHeight > maxHeight || actualWidth > maxWidth) { if (imgRatio < maxRatio) { imgRatio = maxHeight / actualHeight; actualWidth = (int) (imgRatio * actualWidth); actualHeight = (int) maxHeight; } else if (imgRatio > maxRatio) { imgRatio = maxWidth / actualWidth; actualHeight = (int) (imgRatio * actualHeight); actualWidth = (int) maxWidth; } else { actualHeight = (int) maxHeight; actualWidth = (int) maxWidth; } } options.inSampleSize = imageLoadingUtils.calculateInSampleSize(options, actualWidth, actualHeight); options.inJustDecodeBounds = false; options.inDither = false; options.inPurgeable = true; options.inInputShareable = true; options.inTempStorage = new byte[16 * 1024]; try { bmp = BitmapFactory.decodeFile(imageUri, options); } catch (OutOfMemoryError exception) { exception.printStackTrace(); } try { scaledBitmap = Bitmap.createBitmap(actualWidth, actualHeight, Bitmap.Config.ARGB_8888); } catch (OutOfMemoryError exception) { exception.printStackTrace(); } float ratioX = actualWidth / (float) options.outWidth; float ratioY = actualHeight / (float) options.outHeight; float middleX = actualWidth / 2.0f; float middleY = actualHeight / 2.0f; Matrix scaleMatrix = new Matrix(); scaleMatrix.setScale(ratioX, ratioY, middleX, middleY); Canvas canvas = new Canvas(scaledBitmap); canvas.setMatrix(scaleMatrix); canvas.drawBitmap(bmp, middleX - bmp.getWidth() / 2, middleY - bmp.getHeight() / 2, new Paint(Paint.FILTER_BITMAP_FLAG)); ExifInterface exif; try { exif = new ExifInterface(imageUri); int orientation = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION, 0); Log.d("EXIF", "Exif: " + orientation); Matrix matrix = new Matrix(); if (orientation == 6) { matrix.postRotate(90); Log.d("EXIF", "Exif: " + orientation); } else if (orientation == 3) { matrix.postRotate(180); Log.d("EXIF", "Exif: " + orientation); } else if (orientation == 8) { matrix.postRotate(270); Log.d("EXIF", "Exif: " + orientation); } scaledBitmap = Bitmap.createBitmap(scaledBitmap, 0, 0, scaledBitmap.getWidth(), scaledBitmap.getHeight(), matrix, true); } catch (IOException e) { e.printStackTrace(); } FileOutputStream out = null; String filename = null; try { // filename = createImageFile(CreatePostActivity.this, true).getAbsolutePath(); filename = createImageFile(folderName, imagePath).getAbsolutePath(); } catch (IOException e) { e.printStackTrace(); } try { out = new FileOutputStream(filename); scaledBitmap.compress(Bitmap.CompressFormat.JPEG, 100, out); } catch (FileNotFoundException e) { e.printStackTrace(); } return filename; } public static File createImageFile(String folderName, String imagePath) throws IOException { File dir = new File(folderName); if (!dir.exists()) dir.mkdir(); File file = new File(dir + File.separator + new File(imagePath).getName()); if (!file.exists()) { file.createNewFile(); } return file; }
Comments
Post a Comment