How to draw or write text by hand on image selected from gallery in android?

1.5k views Asked by At

Actually I have written a code to select image from gallery,but I dont know how to draw or write a text by hand on it.and Edited image should be saved separately in sdcard.Basically I have to make basic paint app where canvas will be my selected image,and my touch is input to draw a circle or anything.

package listdisplay.example.com.photoedit;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.net.Uri;
import android.os.ParcelFileDescriptor;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Display;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;

import java.io.FileDescriptor;
import java.io.IOException;

public class MainActivity_photoedit extends AppCompatActivity {
    private static final int RORC =0;
    ImageView iview;
    Button button,button2;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main_photoedit);
        iview= (ImageView) findViewById(R.id.imageView);

        button =(Button)findViewById(R.id.button);
        button.setOnClickListener(new View.OnClickListener() {
                                      @Override
                                      public void onClick(View view) {
                                          Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
                                          intent.addCategory(Intent.CATEGORY_OPENABLE);
                                          intent.setType("image/*");
                                          startActivityForResult(intent,RORC);
                                      }
                                  }

        );
}
    @Override
    public  void onActivityResult(int requestCode,int resultCode,Intent resultData){
        if(requestCode==RORC && resultCode==RESULT_OK){
            Uri uri =null;
            if(resultData!=null){
                uri=resultData.getData();
                try {
                    Bitmap bitmap= getBitmapFromUri(uri);



                    iview.setImageBitmap(bitmap);
                }
                catch (IOException e){
                    e.printStackTrace();
                }
            }
        }
    }
    private Bitmap getBitmapFromUri(Uri uri) throws IOException{
        ParcelFileDescriptor parcelFileDescriptor = getContentResolver().openFileDescriptor(uri,"r");
        FileDescriptor fileDescriptor= parcelFileDescriptor.getFileDescriptor();
        Bitmap bitmap = BitmapFactory.decodeFileDescriptor(fileDescriptor);

        parcelFileDescriptor.close();
        return bitmap;
    }
}
2

There are 2 answers

0
jeel raja On

I have find solution for your requirement . So try this,But for that you have to take Drawing-view instead of Image-view to draw or write text on Image which is picked from Gallery.

Hereby, I am posting code.

activity_main.xml :

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="center"
    android:orientation="vertical"
    android:paddingBottom="5dp"
    android:paddingTop="5dp"
    tools:context=".MainActivity">

    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="horizontal">

        <ImageButton
            android:id="@+id/buttonNew"
            android:layout_width="wrap_content"
            android:layout_height="fill_parent"
            android:contentDescription="@string/start_new"
            android:src="@drawable/new_pic" />

        <ImageButton
            android:id="@+id/buttonBrush"
            android:layout_width="wrap_content"
            android:layout_height="fill_parent"
            android:contentDescription="@string/brush"
            android:src="@drawable/brush" />

        <ImageButton
            android:id="@+id/buttonErase"
            android:layout_width="wrap_content"
            android:layout_height="fill_parent"
            android:contentDescription="@string/erase"
            android:src="@drawable/eraser" />

        <ImageButton
            android:id="@+id/buttonSave"
            android:layout_width="wrap_content"
            android:layout_height="fill_parent"
            android:contentDescription="@string/save"
            android:src="@drawable/save" />

        <ImageButton
            android:id="@+id/buttonPickImage"
            android:layout_width="wrap_content"
            android:layout_height="fill_parent"
            android:contentDescription="@string/save"
            android:src="@drawable/save" />

    </LinearLayout>

    <com.wordpress.priyankvex.paintapp.DrawingView
        android:id="@+id/drawing"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_marginBottom="3dp"
        android:layout_marginLeft="5dp"
        android:layout_marginRight="5dp"
        android:layout_marginTop="3dp"
        android:layout_weight="1"
        android:background="@color/white" />

    <!-- Color pallet -->
    <LinearLayout
        android:id="@+id/paint_colors"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="horizontal">

        <ImageButton
            android:layout_width="@dimen/large_brush"
            android:layout_height="@dimen/large_brush"
            android:layout_margin="2dp"
            android:background="@color/skin"
            android:contentDescription="@string/paint"
            android:onClick="paintClicked"
            android:src="@drawable/pallet"
            android:tag="@color/skin" />

        <ImageButton
            android:layout_width="@dimen/large_brush"
            android:layout_height="@dimen/large_brush"
            android:layout_margin="2dp"
            android:background="@color/black"
            android:contentDescription="@string/paint"
            android:onClick="paintClicked"
            android:src="@drawable/pallet"
            android:tag="@color/black" />

        <ImageButton
            android:layout_width="@dimen/large_brush"
            android:layout_height="@dimen/large_brush"
            android:layout_margin="2dp"
            android:background="@color/red"
            android:contentDescription="@string/paint"
            android:onClick="paintClicked"
            android:src="@drawable/pallet"
            android:tag="@color/red" />

        <ImageButton
            android:layout_width="@dimen/large_brush"
            android:layout_height="@dimen/large_brush"
            android:layout_margin="2dp"
            android:background="@color/green"
            android:contentDescription="@string/paint"
            android:onClick="paintClicked"
            android:src="@drawable/pallet"
            android:tag="@color/green" />

        <ImageButton
            android:layout_width="@dimen/large_brush"
            android:layout_height="@dimen/large_brush"
            android:layout_margin="2dp"
            android:background="@color/blue"
            android:contentDescription="@string/paint"
            android:onClick="paintClicked"
            android:src="@drawable/pallet"
            android:tag="@color/blue" />

        <ImageButton
            android:layout_width="@dimen/large_brush"
            android:layout_height="@dimen/large_brush"
            android:layout_margin="2dp"
            android:background="@color/yellow"
            android:contentDescription="@string/paint"
            android:onClick="paintClicked"
            android:src="@drawable/pallet"
            android:tag="@color/yellow" />

    </LinearLayout>

</LinearLayout>

MainActivity.java :

import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Toast;

import java.util.UUID;


public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    private DrawingView mDrawingView;
    private ImageButton currPaint, drawButton, eraseButton, newButton, saveButton, buttonPickImage;
    private float smallBrush, mediumBrush, largeBrush;
    private final int RESULT_LOAD_IMAGE = 20;
    private Uri pickedImage;
    private String imagePath = "";
    public Bitmap PaintBitmap;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        mDrawingView = (DrawingView) findViewById(R.id.drawing);
        // Getting the initial paint color.
        LinearLayout paintLayout = (LinearLayout) findViewById(R.id.paint_colors);
        // 0th child is white color, so selecting first child to give black as initial color.
        currPaint = (ImageButton) paintLayout.getChildAt(1);
        currPaint.setImageDrawable(getResources().getDrawable(R.drawable.pallet_pressed));
        drawButton = (ImageButton) findViewById(R.id.buttonBrush);
        drawButton.setOnClickListener(this);
        eraseButton = (ImageButton) findViewById(R.id.buttonErase);
        eraseButton.setOnClickListener(this);
        newButton = (ImageButton) findViewById(R.id.buttonNew);
        newButton.setOnClickListener(this);
        saveButton = (ImageButton) findViewById(R.id.buttonSave);
        saveButton.setOnClickListener(this);
        buttonPickImage = (ImageButton) findViewById(R.id.buttonPickImage);
        buttonPickImage.setOnClickListener(this);

        smallBrush = getResources().getInteger(R.integer.small_size);
        mediumBrush = getResources().getInteger(R.integer.medium_size);
        largeBrush = getResources().getInteger(R.integer.large_size);

        // Set the initial brush size
        mDrawingView.setBrushSize(mediumBrush);
    }

    /**
     * Method is called when color is clicked from pallet.
     *
     * @param view ImageButton on which click took place.
     */
    public void paintClicked(View view) {
        if (view != currPaint) {
            // Update the color
            ImageButton imageButton = (ImageButton) view;
            String colorTag = imageButton.getTag().toString();
            mDrawingView.setColor(colorTag);
            // Swap the backgrounds for last active and currently active image button.
            imageButton.setImageDrawable(getResources().getDrawable(R.drawable.pallet_pressed));
            currPaint.setImageDrawable(getResources().getDrawable(R.drawable.pallet));
            currPaint = (ImageButton) view;
            mDrawingView.setErase(false);
            mDrawingView.setBrushSize(mDrawingView.getLastBrushSize());
        }
    }

    @Override
    public void onClick(View v) {
        int id = v.getId();
        switch (id) {
            case R.id.buttonBrush:
                // Show brush size chooser dialog
                showBrushSizeChooserDialog();
                break;
            case R.id.buttonErase:
                // Show eraser size chooser dialog
                showEraserSizeChooserDialog();
                break;
            case R.id.buttonNew:
                // Show new painting alert dialog
                showNewPaintingAlertDialog();
                break;
            case R.id.buttonSave:
                // Show save painting confirmation dialog.
                showSavePaintingConfirmationDialog();
                break;

            case R.id.buttonPickImage:
                // Show save painting confirmation dialog.
                Intent i = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                startActivityForResult(i, RESULT_LOAD_IMAGE);
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK) {
            pickedImage = data.getData();
            String[] filePath = {MediaStore.Images.Media.DATA};
            Cursor cursor = getContentResolver().query(pickedImage, filePath, null, null, null);
            cursor.moveToFirst();
            imagePath = cursor.getString(cursor.getColumnIndex(filePath[0]));
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {

                // set Gallery Image to Drawing-view
                if (imagePath != null) {
                    PaintBitmap = getResizeBitmap(imagePath);
                    BitmapDrawable ob = new BitmapDrawable(getResources(), PaintBitmap);
                    mDrawingView.setBackgroundDrawable(ob);
                }
            }
        }
    }

    public static Bitmap getResizeBitmap(String path) {
        BitmapFactory.Options op = new BitmapFactory.Options();
        op.inPreferredConfig = Bitmap.Config.ARGB_8888;
        Bitmap bmap = BitmapFactory.decodeFile(path, op);
        int nh = (int) (bmap.getHeight() * (1024.0 / bmap.getWidth()));
        Bitmap bitmapThumbnail = Bitmap.createScaledBitmap(bmap, 1024, nh, true);
        int bitmapWidthMain = bitmapThumbnail.getWidth();
        int bitmapHeightMain = bitmapThumbnail.getHeight();
        return bitmapThumbnail;
    }
    private void showBrushSizeChooserDialog() {
        final Dialog brushDialog = new Dialog(this);
        brushDialog.setContentView(R.layout.dialog_brush_size);
        brushDialog.setTitle("Brush size:");
        ImageButton smallBtn = (ImageButton) brushDialog.findViewById(R.id.small_brush);
        smallBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mDrawingView.setBrushSize(smallBrush);
                mDrawingView.setLastBrushSize(smallBrush);
                brushDialog.dismiss();
            }
        });
        ImageButton mediumBtn = (ImageButton) brushDialog.findViewById(R.id.medium_brush);
        mediumBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mDrawingView.setBrushSize(mediumBrush);
                mDrawingView.setLastBrushSize(mediumBrush);
                brushDialog.dismiss();
            }
        });

        ImageButton largeBtn = (ImageButton) brushDialog.findViewById(R.id.large_brush);
        largeBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mDrawingView.setBrushSize(largeBrush);
                mDrawingView.setLastBrushSize(largeBrush);
                brushDialog.dismiss();
            }
        });
        mDrawingView.setErase(false);
        brushDialog.show();
    }

    private void showEraserSizeChooserDialog() {
        final Dialog brushDialog = new Dialog(this);
        brushDialog.setTitle("Eraser size:");
        brushDialog.setContentView(R.layout.dialog_brush_size);
        ImageButton smallBtn = (ImageButton) brushDialog.findViewById(R.id.small_brush);
        smallBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mDrawingView.setErase(true);
                mDrawingView.setBrushSize(smallBrush);
                brushDialog.dismiss();
            }
        });
        ImageButton mediumBtn = (ImageButton) brushDialog.findViewById(R.id.medium_brush);
        mediumBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mDrawingView.setErase(true);
                mDrawingView.setBrushSize(mediumBrush);
                brushDialog.dismiss();
            }
        });
        ImageButton largeBtn = (ImageButton) brushDialog.findViewById(R.id.large_brush);
        largeBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mDrawingView.setErase(true);
                mDrawingView.setBrushSize(largeBrush);
                brushDialog.dismiss();
            }
        });
        brushDialog.show();
    }

    private void showNewPaintingAlertDialog() {
        AlertDialog.Builder newDialog = new AlertDialog.Builder(this);
        newDialog.setTitle("New drawing");
        newDialog.setMessage("Start new drawing (you will lose the current drawing)?");
        newDialog.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
                mDrawingView.startNew();
                dialog.dismiss();
            }
        });
        newDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
                dialog.cancel();
            }
        });
        newDialog.show();
    }

    private void showSavePaintingConfirmationDialog() {
        AlertDialog.Builder saveDialog = new AlertDialog.Builder(this);
        saveDialog.setTitle("Save drawing");
        saveDialog.setMessage("Save drawing to device Gallery?");
        saveDialog.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
                //save drawing
                mDrawingView.setDrawingCacheEnabled(true);
                String imgSaved = MediaStore.Images.Media.insertImage(
                        getContentResolver(), mDrawingView.getDrawingCache(),
                        UUID.randomUUID().toString() + ".png", "drawing");
                if (imgSaved != null) {
                    Toast savedToast = Toast.makeText(getApplicationContext(),
                            "Drawing saved to Gallery!", Toast.LENGTH_SHORT);
                    savedToast.show();
                } else {
                    Toast unsavedToast = Toast.makeText(getApplicationContext(),
                            "Oops! Image could not be saved.", Toast.LENGTH_SHORT);
                    unsavedToast.show();
                }
                // Destroy the current cache.
                mDrawingView.destroyDrawingCache();
            }
        });
        saveDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
                dialog.cancel();
            }
        });
        saveDialog.show();
    }

}

Manifest.xml :

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />

Try This code, It include brush for draw text on image with different brush size,eraser and color picker to draw text in different colors on text and yes, It will save image with text in gallery.

Hereby, i am attaching screenshot,

enter image description here

Hope, it will help you. :)

0
jeel raja On

Also, there is another way to do like this is using FingerPaint Api.

For that download code from here,

"https://github.com/nikt/Finger-Paint"

Yes,It also not using Image-view, But it will pick image from gallery and set it into Draw-view and paint on that image.You can also try this.