Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package ru.happy_giraffe.mypediatrician.utils;
- import android.content.Context;
- import android.content.res.AssetFileDescriptor;
- import android.database.Cursor;
- import android.graphics.Bitmap;
- import android.graphics.BitmapFactory;
- import android.graphics.Matrix;
- import android.media.ExifInterface;
- import android.net.Uri;
- import android.provider.MediaStore;
- import android.provider.OpenableColumns;
- import com.loopj.android.http.AsyncHttpClient;
- import com.loopj.android.http.RequestParams;
- import org.apache.commons.io.output.ByteArrayOutputStream;
- import org.json.JSONArray;
- import org.json.JSONObject;
- import java.io.ByteArrayInputStream;
- import java.io.File;
- import java.io.FileNotFoundException;
- import java.io.IOException;
- import java.io.InputStream;
- import cz.msebera.android.httpclient.Header;
- import ru.happy_giraffe.giraffesdk.Giraffe;
- import ru.happy_giraffe.mypediatrician.BuildConfig;
- import ru.happy_giraffe.mypediatrician.R;
- /**
- * Created by RomanByakov on 15.09.16.
- */
- public class ImageUploader {
- private ImageUploader() {
- }
- private static volatile ImageUploader ourInstance = new ImageUploader();
- public static ImageUploader getInstance() {
- if (ourInstance == null) {
- ourInstance = new ImageUploader();
- }
- return ourInstance;
- }
- public void uploadPhoto(final String fileName, final InputStream myInputStream, Context context, final FileUploadRequestListener listener) {
- AsyncHttpClient client = new AsyncHttpClient();
- client.setTimeout(20000);
- RequestParams requestParams = new RequestParams();
- client.addHeader("access-token", Giraffe.getInstance(context).getCurrentAccessToken());
- client.addHeader("app-id", BuildConfig.appId);
- requestParams.put("photo", myInputStream, fileName, "image/png");
- String url = BuildConfig.host + "/api/photo/";
- String method = "POST";
- client.post(url, requestParams, new JsonHttpResponseHandlerWithLogs(url, method, requestParams) {
- @Override
- public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
- super.onSuccess(statusCode, headers, response);
- listener.onSuccess(response.optString("url"), response.optInt("new_photo_id"));
- }
- @Override
- public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
- super.onFailure(statusCode, headers, responseString, throwable);
- listener.onError("Не удалось загрузить фото");
- }
- @Override
- public void onFailure(int statusCode, Header[] headers, Throwable throwable, JSONObject errorResponse) {
- super.onFailure(statusCode, headers, throwable, errorResponse);
- listener.onError("Не удалось загрузить фото");
- }
- @Override
- public void onFailure(int statusCode, Header[] headers, Throwable throwable, JSONArray errorResponse) {
- super.onFailure(statusCode, headers, throwable, errorResponse);
- listener.onError("Не удалось загрузить фото");
- }
- });
- }
- public String getHtmlPreview(String filePath) {
- return "<img src=\"" + filePath + "\" width=\"100%\" style=\"opacity:0.4;filter:alpha(opacity=40)\">";
- }
- public String getCompletedHtml(String filePath) {
- return "<img src=\"" + filePath + "\" width=\"100%\"><p></p><br>";
- }
- public void prepareAndUpload(String filePath, Context context, boolean isCamera, FileUploadRequestListener listener) {
- Uri uri = null;
- if (isCamera) {
- uri = Uri.fromFile(new File(filePath));
- } else {
- uri = Uri.parse(filePath);
- }
- String name = "photo";
- int orientation = 0;
- // get orientation
- if (isCamera) {
- ExifInterface ei = null;
- try {
- ei = new ExifInterface(filePath);
- } catch (IOException ex) {
- ex.printStackTrace();
- }
- orientation = ei.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_UNDEFINED);
- name = filePath.substring(filePath.lastIndexOf("/") + 1);
- } else {
- Cursor returnCursor = context.getContentResolver().query(uri, null, null, null, null);
- String[] orientationColumn = {MediaStore.Images.Media.ORIENTATION};
- int nameIndex = 0;
- try {
- if (returnCursor != null && returnCursor.moveToFirst()) {
- int index = returnCursor.getColumnIndex(orientationColumn[0]);
- orientation = returnCursor.getInt(index);
- nameIndex = returnCursor.getColumnIndex(OpenableColumns.DISPLAY_NAME);
- // get filename
- name = returnCursor.getString(nameIndex);
- System.out.println("get orientation fin");
- System.out.println("get filename fin");
- returnCursor.close();
- System.out.println("cursor close");
- }
- } catch (Exception er) {
- }
- }
- // get bitmap
- Bitmap bitmap = readBitmap(uri, context);
- System.out.println("get bitmap fin");
- // autorotate
- if (orientation != 0) {
- bitmap = rotateImage(bitmap, new Float(orientation));
- System.out.println("autorotate fin");
- }
- InputStream inputStream = null;
- // get stream
- if (orientation != 0) {
- ByteArrayOutputStream stream = new ByteArrayOutputStream();
- bitmap.compress(Bitmap.CompressFormat.JPEG, 100, stream);
- inputStream = new ByteArrayInputStream(stream.toByteArray());
- if (stream != null) {
- try {
- stream.close();
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- } else {
- System.out.println("without rotate");
- try {
- inputStream = context.getContentResolver().openInputStream(uri);
- } catch (FileNotFoundException e) {
- e.printStackTrace();
- }
- }
- // load photo
- uploadPhoto(name, inputStream, context, listener);
- }
- private Bitmap rotateImage(Bitmap source, float angle) {
- Bitmap retVal;
- Matrix matrix = new Matrix();
- matrix.postRotate(angle);
- retVal = Bitmap.createBitmap(source, 0, 0, source.getWidth(), source.getHeight(), matrix, true);
- return retVal;
- }
- private Bitmap readBitmap(Uri selectedImage, Context context) {
- Bitmap bm = null;
- BitmapFactory.Options options = new BitmapFactory.Options();
- options.inSampleSize = 5;
- AssetFileDescriptor fileDescriptor = null;
- try {
- fileDescriptor = context.getContentResolver().openAssetFileDescriptor(selectedImage, "r");
- } catch (FileNotFoundException e) {
- e.printStackTrace();
- } finally {
- try {
- bm = BitmapFactory.decodeFileDescriptor(fileDescriptor.getFileDescriptor(), null, options);
- fileDescriptor.close();
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- return bm;
- }
- public interface FileUploadRequestListener {
- void onSuccess(String url, int photoId);
- void onError(String error);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement