Search in sources :

Example 1 with Compressor

use of id.zelory.compressor.Compressor in project PhotoBlog-Android-Blog-App by akshayejh.

the class NewPostActivity method onCreate.

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_new_post);
    storageReference = FirebaseStorage.getInstance().getReference();
    firebaseFirestore = FirebaseFirestore.getInstance();
    firebaseAuth = FirebaseAuth.getInstance();
    current_user_id = firebaseAuth.getCurrentUser().getUid();
    newPostToolbar = findViewById(R.id.new_post_toolbar);
    setSupportActionBar(newPostToolbar);
    getSupportActionBar().setTitle("Add New Post");
    getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    newPostImage = findViewById(R.id.new_post_image);
    newPostDesc = findViewById(R.id.new_post_desc);
    newPostBtn = findViewById(R.id.post_btn);
    newPostProgress = findViewById(R.id.new_post_progress);
    newPostImage.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            CropImage.activity().setGuidelines(CropImageView.Guidelines.ON).setMinCropResultSize(512, 512).setAspectRatio(1, 1).start(NewPostActivity.this);
        }
    });
    newPostBtn.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            final String desc = newPostDesc.getText().toString();
            if (!TextUtils.isEmpty(desc) && postImageUri != null) {
                newPostProgress.setVisibility(View.VISIBLE);
                final String randomName = UUID.randomUUID().toString();
                // PHOTO UPLOAD
                File newImageFile = new File(postImageUri.getPath());
                try {
                    compressedImageFile = new Compressor(NewPostActivity.this).setMaxHeight(720).setMaxWidth(720).setQuality(50).compressToBitmap(newImageFile);
                } catch (IOException e) {
                    e.printStackTrace();
                }
                ByteArrayOutputStream baos = new ByteArrayOutputStream();
                compressedImageFile.compress(Bitmap.CompressFormat.JPEG, 100, baos);
                byte[] imageData = baos.toByteArray();
                // PHOTO UPLOAD
                UploadTask filePath = storageReference.child("post_images").child(randomName + ".jpg").putBytes(imageData);
                filePath.addOnCompleteListener(new OnCompleteListener<UploadTask.TaskSnapshot>() {

                    @Override
                    public void onComplete(@NonNull final Task<UploadTask.TaskSnapshot> task) {
                        final String downloadUri = task.getResult().getDownloadUrl().toString();
                        if (task.isSuccessful()) {
                            File newThumbFile = new File(postImageUri.getPath());
                            try {
                                compressedImageFile = new Compressor(NewPostActivity.this).setMaxHeight(100).setMaxWidth(100).setQuality(1).compressToBitmap(newThumbFile);
                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                            ByteArrayOutputStream baos = new ByteArrayOutputStream();
                            compressedImageFile.compress(Bitmap.CompressFormat.JPEG, 100, baos);
                            byte[] thumbData = baos.toByteArray();
                            UploadTask uploadTask = storageReference.child("post_images/thumbs").child(randomName + ".jpg").putBytes(thumbData);
                            uploadTask.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {

                                @Override
                                public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
                                    String downloadthumbUri = taskSnapshot.getDownloadUrl().toString();
                                    Map<String, Object> postMap = new HashMap<>();
                                    postMap.put("image_url", downloadUri);
                                    postMap.put("image_thumb", downloadthumbUri);
                                    postMap.put("desc", desc);
                                    postMap.put("user_id", current_user_id);
                                    postMap.put("timestamp", FieldValue.serverTimestamp());
                                    firebaseFirestore.collection("Posts").add(postMap).addOnCompleteListener(new OnCompleteListener<DocumentReference>() {

                                        @Override
                                        public void onComplete(@NonNull Task<DocumentReference> task) {
                                            if (task.isSuccessful()) {
                                                Toast.makeText(NewPostActivity.this, "Post was added", Toast.LENGTH_LONG).show();
                                                Intent mainIntent = new Intent(NewPostActivity.this, MainActivity.class);
                                                startActivity(mainIntent);
                                                finish();
                                            } else {
                                            }
                                            newPostProgress.setVisibility(View.INVISIBLE);
                                        }
                                    });
                                }
                            }).addOnFailureListener(new OnFailureListener() {

                                @Override
                                public void onFailure(@NonNull Exception e) {
                                // Error handling
                                }
                            });
                        } else {
                            newPostProgress.setVisibility(View.INVISIBLE);
                        }
                    }
                });
            }
        }
    });
}
Also used : Task(com.google.android.gms.tasks.Task) UploadTask(com.google.firebase.storage.UploadTask) HashMap(java.util.HashMap) UploadTask(com.google.firebase.storage.UploadTask) NonNull(android.support.annotation.NonNull) OnSuccessListener(com.google.android.gms.tasks.OnSuccessListener) DocumentReference(com.google.firebase.firestore.DocumentReference) Compressor(id.zelory.compressor.Compressor) Intent(android.content.Intent) IOException(java.io.IOException) ByteArrayOutputStream(java.io.ByteArrayOutputStream) ImageView(android.widget.ImageView) CropImageView(com.theartofdev.edmodo.cropper.CropImageView) View(android.view.View) IOException(java.io.IOException) OnCompleteListener(com.google.android.gms.tasks.OnCompleteListener) File(java.io.File) OnFailureListener(com.google.android.gms.tasks.OnFailureListener)

Example 2 with Compressor

use of id.zelory.compressor.Compressor in project PhotoBlog-Android-Blog-App by akshayejh.

the class SetupActivity method onCreate.

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_setup);
    Toolbar setupToolbar = findViewById(R.id.setupToolbar);
    setSupportActionBar(setupToolbar);
    getSupportActionBar().setTitle("Account Setup");
    firebaseAuth = FirebaseAuth.getInstance();
    user_id = firebaseAuth.getCurrentUser().getUid();
    firebaseFirestore = FirebaseFirestore.getInstance();
    storageReference = FirebaseStorage.getInstance().getReference();
    setupImage = findViewById(R.id.setup_image);
    setupName = findViewById(R.id.setup_name);
    setupBtn = findViewById(R.id.setup_btn);
    setupProgress = findViewById(R.id.setup_progress);
    setupProgress.setVisibility(View.VISIBLE);
    setupBtn.setEnabled(false);
    firebaseFirestore.collection("Users").document(user_id).get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {

        @Override
        public void onComplete(@NonNull Task<DocumentSnapshot> task) {
            if (task.isSuccessful()) {
                if (task.getResult().exists()) {
                    String name = task.getResult().getString("name");
                    String image = task.getResult().getString("image");
                    mainImageURI = Uri.parse(image);
                    setupName.setText(name);
                    RequestOptions placeholderRequest = new RequestOptions();
                    placeholderRequest.placeholder(R.drawable.default_image);
                    Glide.with(SetupActivity.this).setDefaultRequestOptions(placeholderRequest).load(image).into(setupImage);
                }
            } else {
                String error = task.getException().getMessage();
                Toast.makeText(SetupActivity.this, "(FIRESTORE Retrieve Error) : " + error, Toast.LENGTH_LONG).show();
            }
            setupProgress.setVisibility(View.INVISIBLE);
            setupBtn.setEnabled(true);
        }
    });
    setupBtn.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            final String user_name = setupName.getText().toString();
            if (!TextUtils.isEmpty(user_name) && mainImageURI != null) {
                setupProgress.setVisibility(View.VISIBLE);
                if (isChanged) {
                    user_id = firebaseAuth.getCurrentUser().getUid();
                    File newImageFile = new File(mainImageURI.getPath());
                    try {
                        compressedImageFile = new Compressor(SetupActivity.this).setMaxHeight(125).setMaxWidth(125).setQuality(50).compressToBitmap(newImageFile);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    ByteArrayOutputStream baos = new ByteArrayOutputStream();
                    compressedImageFile.compress(Bitmap.CompressFormat.JPEG, 100, baos);
                    byte[] thumbData = baos.toByteArray();
                    UploadTask image_path = storageReference.child("profile_images").child(user_id + ".jpg").putBytes(thumbData);
                    image_path.addOnCompleteListener(new OnCompleteListener<UploadTask.TaskSnapshot>() {

                        @Override
                        public void onComplete(@NonNull Task<UploadTask.TaskSnapshot> task) {
                            if (task.isSuccessful()) {
                                storeFirestore(task, user_name);
                            } else {
                                String error = task.getException().getMessage();
                                Toast.makeText(SetupActivity.this, "(IMAGE Error) : " + error, Toast.LENGTH_LONG).show();
                                setupProgress.setVisibility(View.INVISIBLE);
                            }
                        }
                    });
                } else {
                    storeFirestore(null, user_name);
                }
            }
        }
    });
    setupImage.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                if (ContextCompat.checkSelfPermission(SetupActivity.this, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
                    Toast.makeText(SetupActivity.this, "Permission Denied", Toast.LENGTH_LONG).show();
                    ActivityCompat.requestPermissions(SetupActivity.this, new String[] { Manifest.permission.READ_EXTERNAL_STORAGE }, 1);
                } else {
                    BringImagePicker();
                }
            } else {
                BringImagePicker();
            }
        }
    });
}
Also used : Task(com.google.android.gms.tasks.Task) UploadTask(com.google.firebase.storage.UploadTask) RequestOptions(com.bumptech.glide.request.RequestOptions) Compressor(id.zelory.compressor.Compressor) IOException(java.io.IOException) ByteArrayOutputStream(java.io.ByteArrayOutputStream) CircleImageView(de.hdodenhof.circleimageview.CircleImageView) CropImageView(com.theartofdev.edmodo.cropper.CropImageView) View(android.view.View) DocumentSnapshot(com.google.firebase.firestore.DocumentSnapshot) UploadTask(com.google.firebase.storage.UploadTask) OnCompleteListener(com.google.android.gms.tasks.OnCompleteListener) NonNull(android.support.annotation.NonNull) File(java.io.File) Toolbar(android.support.v7.widget.Toolbar)

Example 3 with Compressor

use of id.zelory.compressor.Compressor in project Lets-Chat by kshitiz1007.

the class SettingActivity method onActivityResult.

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    // -----STARTING GALLERY----
    if (requestCode == GALLERY_PICK && resultCode == RESULT_OK) {
        Uri sourceUri = data.getData();
        // -------CROPPING IMAGE AND SETTING MINIMUM SIZE TO 500 , 500------
        CropImage.activity(sourceUri).setAspectRatio(1, 1).setMinCropWindowSize(500, 500).start(SettingActivity.this);
    }
    // ------START CROP IMAGE ACTIVITY------
    if (requestCode == CropImage.CROP_IMAGE_ACTIVITY_REQUEST_CODE) {
        // ------CROP IMAGE RESULT------
        CropImage.ActivityResult result = CropImage.getActivityResult(data);
        if (resultCode == RESULT_OK) {
            mProgressDialog.setTitle("Uploading Image");
            mProgressDialog.setMessage("Please wait while we process and upload the image...");
            mProgressDialog.setCancelable(false);
            mProgressDialog.setProgress(ProgressDialog.STYLE_SPINNER);
            mProgressDialog.show();
            Uri resultUri = result.getUri();
            File thumb_filepath = new File(resultUri.getPath());
            try {
                // --------COMPRESSING IMAGE--------
                Bitmap thumb_bitmap = new Compressor(this).setMaxWidth(200).setMaxHeight(200).setQuality(75).compressToBitmap(thumb_filepath);
                ByteArrayOutputStream baos = new ByteArrayOutputStream();
                thumb_bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
                thumb_bytes = baos.toByteArray();
            } catch (IOException e) {
                e.printStackTrace();
            }
            StorageReference filepath = mStorageReference.child("profile_image").child(uid + ".jpg");
            final StorageReference thumb_file_path = mStorageReference.child("profile_image").child("thumbs").child(uid + ".jpg");
            // ------STORING IMAGE IN FIREBASE STORAGE--------
            filepath.putFile(resultUri).addOnCompleteListener(new OnCompleteListener<UploadTask.TaskSnapshot>() {

                @Override
                public void onComplete(@NonNull Task<UploadTask.TaskSnapshot> task) {
                    if (task.isSuccessful()) {
                        @SuppressWarnings("VisibleForTests") final String downloadUrl = task.getResult().getDownloadUrl().toString();
                        UploadTask uploadTask = thumb_file_path.putBytes(thumb_bytes);
                        // ---------- STORING THUMB IMAGE INTO STORAGE REFERENCE --------
                        uploadTask.addOnCompleteListener(new OnCompleteListener<UploadTask.TaskSnapshot>() {

                            @Override
                            public void onComplete(@NonNull Task<UploadTask.TaskSnapshot> thumb_task) {
                                @SuppressWarnings("VisibleForTests") String thumb_download_url = thumb_task.getResult().getDownloadUrl().toString();
                                if (thumb_task.isSuccessful()) {
                                    Map update_HashMap = new HashMap();
                                    update_HashMap.put("image", downloadUrl);
                                    update_HashMap.put("thumb_image", thumb_download_url);
                                    // --------ADDING URL INTO DATABASE REFERENCE--------
                                    mDatabaseReference.updateChildren(update_HashMap).addOnCompleteListener(new OnCompleteListener<Void>() {

                                        @Override
                                        public void onComplete(@NonNull Task<Void> task) {
                                            if (task.isSuccessful()) {
                                                mProgressDialog.dismiss();
                                                Toast.makeText(SettingActivity.this, "Uploaded Successfuly...", Toast.LENGTH_SHORT).show();
                                            } else {
                                                mProgressDialog.dismiss();
                                                Toast.makeText(getApplicationContext(), " Image is not uploading...", Toast.LENGTH_SHORT).show();
                                            }
                                        }
                                    });
                                } else {
                                    mProgressDialog.dismiss();
                                    Toast.makeText(getApplicationContext(), " Error in uploading Thumbnail..", Toast.LENGTH_SHORT).show();
                                }
                            }
                        });
                    } else {
                        mProgressDialog.dismiss();
                        Toast.makeText(getApplicationContext(), " Image is not uploading...", Toast.LENGTH_SHORT).show();
                    }
                }
            });
        } else if (resultCode == CropImage.CROP_IMAGE_ACTIVITY_RESULT_ERROR_CODE) {
            Exception error = result.getError();
        }
    }
}
Also used : Task(com.google.android.gms.tasks.Task) UploadTask(com.google.firebase.storage.UploadTask) HashMap(java.util.HashMap) Uri(android.net.Uri) CropImage(com.theartofdev.edmodo.cropper.CropImage) Bitmap(android.graphics.Bitmap) UploadTask(com.google.firebase.storage.UploadTask) NonNull(android.support.annotation.NonNull) StorageReference(com.google.firebase.storage.StorageReference) Compressor(id.zelory.compressor.Compressor) ByteArrayOutputStream(java.io.ByteArrayOutputStream) IOException(java.io.IOException) IOException(java.io.IOException) OnCompleteListener(com.google.android.gms.tasks.OnCompleteListener) File(java.io.File) HashMap(java.util.HashMap) Map(java.util.Map)

Aggregations

NonNull (android.support.annotation.NonNull)3 OnCompleteListener (com.google.android.gms.tasks.OnCompleteListener)3 Task (com.google.android.gms.tasks.Task)3 UploadTask (com.google.firebase.storage.UploadTask)3 Compressor (id.zelory.compressor.Compressor)3 ByteArrayOutputStream (java.io.ByteArrayOutputStream)3 File (java.io.File)3 IOException (java.io.IOException)3 View (android.view.View)2 CropImageView (com.theartofdev.edmodo.cropper.CropImageView)2 HashMap (java.util.HashMap)2 Intent (android.content.Intent)1 Bitmap (android.graphics.Bitmap)1 Uri (android.net.Uri)1 Toolbar (android.support.v7.widget.Toolbar)1 ImageView (android.widget.ImageView)1 RequestOptions (com.bumptech.glide.request.RequestOptions)1 OnFailureListener (com.google.android.gms.tasks.OnFailureListener)1 OnSuccessListener (com.google.android.gms.tasks.OnSuccessListener)1 DocumentReference (com.google.firebase.firestore.DocumentReference)1