I am making a meme generator app for my android course. I've gotten an API to generate 100 popular memes, when one is clicked it takes you to the EditMemeActivity, where you can type in the upper and lower text. Then, there is a Create Meme button that will take you to the MemeActivity where you will eventually be able to save/share with friends. Currently, when the create meme button is clicked, the meme picture is converted to a Bitmap, and that displays fine on the next page. I want to be able to save the upper and lower text entered by the user on the image as a Bitmap. Because some meme images vary in size, I have a black background around them set to about 400X300 pixels, so I would love to be able to capture that entire imageview AND set put the inputted text in. Here's my code from the two activities:
public class EditMemeActivity extends AppCompatActivity {
#Bind(R.id.editMemeImage) ImageView mEditMemeImage;
#Bind(R.id.editUpperText) EditText mEditUpperText;
#Bind(R.id.editLowerText) EditText mEditLowerText;
#Bind(R.id.saveMeme) Button mSaveMeme;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_edit_meme);
ButterKnife.bind(this);
Intent intent = getIntent();
String image = intent.getStringExtra("image");
final String upper = mEditUpperText.getText().toString();
final String lower = mEditLowerText.getText().toString();
final Bitmap memeBitmap = getBitmapFromURL(image);
Picasso.with(EditMemeActivity.this).load(image).into(mEditMemeImage);
mSaveMeme.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(EditMemeActivity.this, MemeActivity.class);
intent.putExtra("bitmap", memeBitmap);
intent.putExtra("upper", upper);
intent.putExtra("lower", lower);
startActivity(intent);
}
});
}
public static Bitmap getBitmapFromURL(String image) {
try {
URL url = new URL(image);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoInput(true);
connection.connect();
InputStream input = connection.getInputStream();
Bitmap myBitmap = BitmapFactory.decodeStream(input);
return myBitmap;
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
}
public class MemeActivity extends AppCompatActivity {
#Bind(R.id.memeImageView) ImageView mMemeImageView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_meme);
ButterKnife.bind(this);
Intent intent = getIntent();
String upperText = intent.getStringExtra("upper");
String lowerText = intent.getStringExtra("lower");
byte[] byteArray = getIntent().getByteArrayExtra("bitmap");
Bitmap bitmap = BitmapFactory.decodeByteArray(byteArray, 0, byteArray.length);
mMemeImageView.setImageBitmap(bitmap);
}
}
code to get bitmap from imageView
Bitmap bitmap = ((BitmapDrawable)imageView.getDrawable()).getBitmap();
Bitmap implements Parcelable, so you could always pass it in the intent:
Intent intent = new Intent(this, NewActivity.class);
intent.putExtra("key", bitmap);
getting the bitmap in another activity
Intent intent = getIntent();
Bitmap bitmap = (Bitmap) intent.getParcelableExtra("key");
try this
Intent intent = new Intent();
Bundle bundle = new Bundle();
bundle.putParcelable("bitmap",bitmap);
intent.putExtras(bundle);
You can use my code to convert image to Bitmap
public static Bitmap drawableToBitmap(Drawable drawable) {
if (drawable instanceof BitmapDrawable) {
return ((BitmapDrawable) drawable).getBitmap();
}
int width = drawable.getIntrinsicWidth();
width = width > 0 ? width : 1;
int height = drawable.getIntrinsicHeight();
height = height > 0 ? height : 1;
Bitmap bitmap = Bitmap.createBitmap(width, height,
Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
drawable.setBounds(0, 0, canvas.getWidth(), canvas.getHeight());
drawable.draw(canvas);
return bitmap;
}
And pass bitmap to another activity Link
Note : careful with large bitmap it
can cause errors
Solution :
Save image into SDCard and in next activity set this image into ImageView.
...
Related
I uploaded an Image from my Internal Storage and want now to pass this
selected Image to a new Activity. I do not pass an Image from the
drawable. I pass an Image which I selected from my Internal Storage. I
tried to pass this Image via the R.id
ImageView imageView_selectedImage;
imageView_selectedImage =(ImageView)findViewById(R.id.imageView_selectedImage);
Button button_goToNextActivity = (Button) findViewById(R.id.button_goToNextActivity);
button_goToNextActivity.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(this, nextActivity.class);
intent.putExtra("resId", R.id.selectedImage);
startActivity(intent);
}
}
imageView.invalidate();
BitmapDrawable drawable = (BitmapDrawable) imageView.getDrawable();
Bitmap bitmap = drawable.getBitmap();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 90, baos);
byte[] b = baos.toByteArray();
String imageEncoded = Base64.encodeToString(b, Base64.DEFAULT);
Then pass the byte array to the next activity.
Intent intent = new Intent(this, nextActivity.class);
intent.putExtra("image", imageEncoded);
startActivity(intent);
Get the byte from the intent second activity.
Bitmap bmp;
byte[] byteArray = getIntent().getByteArrayExtra("image");
bmp = BitmapFactory.decodeByteArray(byteArray, 0, byteArray.length);
Set the bitmap to the imageview of the second activty
imageview.setImageBitmap(bmp);
Don't pass imageview to next activity.
You can pass uri of Image which is selected from gallery.\
Get Uri for selected image in onActivityResult method like below code:
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == SELECT_GALLERY) {
if (data != null) {
imageSelectedFromGallery(data);
pictureUri=data.getData();
imageView_selectedImage.setImageURI(pictureUri);
}
}
}
Note**: make pictureUri instance variable instead of local variable.
Pass Image Uri to next Activity like below code:
Intent intent=new Intent(Main2Activity.this,NextActivity.class);
intent.putExtra("pictureUri",pictureUri);
startActivity(intent);
Get Image Uri in Next Activity and set into imageView :
ImageView imageview=findViewById(R.id.imageview);
Bundle bundle=getIntent().getExtras();
if(bundle!=null) {
String pictureUri = bundle.getString("pictureUri");
imageview.setImageURI( Uri.parse(pictureUri));
}
I hope its work for you.
I am new to android. I am trying to capture the image and store it in firebase. Since we need to convert the image to string and then store it in firebase, I am using the base64 algorithm.
The methods for capturing image and storing it in the database is :
public void capturePhoto(View v) {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, CAMERA_REQUEST);
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == CAMERA_REQUEST && resultCode == RESULT_OK) {
Bitmap photo = (Bitmap) data.getExtras().get("data");
ImageView imageView = (ImageView) findViewById(R.id.imageView);
imageView.setImageBitmap(photo);
}
}
public void storeDatabase(View v)
{
EditText editRollno = (EditText) findViewById(R.id.rollno);
EditText editname = (EditText) findViewById(R.id.name);
EditText editmarks = (EditText) findViewById(R.id.marks);
Firebase ref1 = ref.child("student_information").child("Student" + n);
ref1.child("Name").setValue(editname.getText().toString());
ref1.child("Rollno").setValue(editRollno.getText().toString());
ref1.child("Marks").setValue(editmarks.getText().toString());
Bitmap bmp = BitmapFactory.decodeResource(getResources(), R.drawable.abc);//your image
ByteArrayOutputStream bYtE = new ByteArrayOutputStream();
bmp.compress(Bitmap.CompressFormat.PNG, 100, bYtE);
bmp.recycle();
byte[] byteArray = bYtE.toByteArray();
imageFile = Base64.encodeToString(byteArray, Base64.DEFAULT);
ref1.child("Image").setValue(imageFile);
n++;
}
When I click on the submit button, it takes a lot of time to upload the values. Moreover, many a times I can see the line
Skipped 537 frames! The application may be doing too much work on its main thread.
in the Android Monitor.
If I comment the image processing lines, it is working all fine.
Can somebody please tell me how to avoid such error so that the image is uploaded instantly in my database.
For storing it to the database, I would definitely use AsyncTask for this one. So, what you could have is a separate class that does the following:
private class ImageDBManager extends AsyncTask< String, Integer, Void> {
protected Long doInBackground(String... items) {
int count = items.length;
String editRoll = items[0];
String editName = items[1];
String editMarks = items[2];
Firebase ref1 = ref.child("student_information").child("Student" + n);
ref1.child("Name").setValue(editname.getText().toString());
ref1.child("Rollno").setValue(editRoll);
ref1.child("Marks").setValue(editName);
Bitmap bmp = BitmapFactory.decodeResource(getResources(), R.drawable.abc);//your image
ByteArrayOutputStream bYtE = new ByteArrayOutputStream();
bmp.compress(Bitmap.CompressFormat.PNG, 100, bYtE);
bmp.recycle();
byte[] byteArray = bYtE.toByteArray();
imageFile = Base64.encodeToString(byteArray, Base64.DEFAULT);
ref1.child("Image").setValue(imageFile);
}
protected void onProgressUpdate(Integer... progress) {
setProgressPercent(progress[0]);
}
protected void onPostExecute(){
}
}
And then call it like this:
public void storeDatabase(View v) {
ImageDBManager manager = new ImageDBManager();
EditText editRollno = (EditText) findViewById(R.id.rollno);
EditText editname = (EditText) findViewById(R.id.name);
EditText editmarks = (EditText) findViewById(R.id.marks);
manager.execute(new String[] { editRollno.getText(), editname.getText(), editmarks.getText() }
}
If you are capturing the image from the camera, the best reference is here
http://developer.android.com/training/camera/photobasics.html
it's the same idea of starting an activity and implementing onActivityForResult where you get the data from the extras in the result, so instead of getting the bitmap from the R.drawable.abc, you'd get it like this in onActivityForResult
Bitmap imageBitmap = (Bitmap) extras.get("data");
In my application, I have an activity where we can capture the image from camera on button click using intent and set the captured image into imageview. Its working absolutely fine.
But now i want the image in specific dimensions. For example, in my case the dimensions of my image view is 150dp * 150dp. So i want that the dimensions of image captured by camera should also always be 150dp * 150dp in order to fit perfectly. How can i do this?
Here's my main activity.
public class MainActivity extends Activity implements OnClickListener {
Button btnTackPic;
TextView tvHasCamera, tvHasCameraApp;
ImageView ivThumbnailPhoto;
Bitmap bitMap;
static int TAKE_PICTURE = 1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Get reference to views
tvHasCamera = (TextView) findViewById(R.id.tvHasCamera);
tvHasCameraApp = (TextView) findViewById(R.id.tvHasCameraApp);
btnTackPic = (Button) findViewById(R.id.btnTakePic);
ivThumbnailPhoto = (ImageView) findViewById(R.id.ivThumbnailPhoto);
// Does your device have a camera?
if(hasCamera()){
tvHasCamera.setBackgroundColor(0xFF00CC00);
tvHasCamera.setText("You have Camera");
}
// Do you have Camera Apps?
if(hasDefualtCameraApp(MediaStore.ACTION_IMAGE_CAPTURE)){
tvHasCameraApp.setBackgroundColor(0xFF00CC00);
tvHasCameraApp.setText("You have Camera Apps");
}
// add onclick listener to the button
btnTackPic.setOnClickListener(this);
}
// on button "btnTackPic" is clicked
#Override
public void onClick(View view) {
// create intent with ACTION_IMAGE_CAPTURE action
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
//Edit to save picture
File file = new File(Environment.getExternalStorageDirectory(), "my-photo.jpg");
Uri photoPath = Uri.fromFile(file);
intent.putExtra(MediaStore.EXTRA_OUTPUT, photoPath);
// start camera activity
startActivityForResult(intent, TAKE_PICTURE);
}
// The Android Camera application encodes the photo in the return Intent delivered to onActivityResult()
// as a small Bitmap in the extras, under the key "data"
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
if (requestCode == TAKE_PICTURE && resultCode== RESULT_OK && intent != null){
// get bundle
Bundle extras = intent.getExtras();
// get
bitMap = (Bitmap) extras.get("data");
ivThumbnailPhoto.setImageBitmap(bitMap);
}
}
// method to check you have a Camera
private boolean hasCamera(){
return getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA);
}
// method to check you have Camera Apps
private boolean hasDefualtCameraApp(String action){
final PackageManager packageManager = getPackageManager();
final Intent intent = new Intent(action);
List<ResolveInfo> list = packageManager.queryIntentActivities(intent, PackageManager.MATCH_DEFAULT_ONLY);
return list.size() > 0;
}
}
Thanks in advance.
You need to scale your Bitmap like the following code:
Bitmap originalBitmap = <the original bitmap>;
Bitmap resizedBitmap = Bitmap.createScaledBitmap(
originalBitmap, newWidth, newHeight, false);
Hence according to your requirement,the resized bitmap must be generated as:
Bitmap resizedBitmap = Bitmap.createScaledBitmap(
bitMap, 150,150, false);
Note:Here 150 is measured in pixels,so you have to calculate 150dp to pixel and then place it.
Can anyone tell me how to convert imageview to bitmap? In my app, i'm accessing the gallery and getting a bitmap of a picture into an imageview, then using picasso, i'm resizing the images that are too big to directly uploaded to parse. I can resize the image in the image view using picasso but how do i get the bitmap from the image view to upload to parse? this is my code..
public static final int IMAGE_GALLERY_REQUEST = 20;
private ImageView imgPicture;
public Bitmap image;
public void openGallery(View view){
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);//
startActivityForResult(Intent.createChooser(intent, "Select Picture"),IMAGE_GALLERY_REQUEST);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
// if we are here, everything processed successfully.
if (requestCode == IMAGE_GALLERY_REQUEST) {
Uri imageUri = data.getData();
InputStream inputStream;
try {
inputStream = getContentResolver().openInputStream(imageUri);
image = BitmapFactory.decodeStream(inputStream);
height= image.getHeight();
h= String.valueOf(height);
width= image.getWidth();
w= String.valueOf(width);
if (width>800 || height>600)
{
Picasso.with(this)
.load(imageUri)
.resize(800,600)
.centerCrop()
.into(imgPicture);
// imgPicture.setImageBitmap(image);
//what should i write here to convert this imageview to bitmap? and then later use that bitmap to upload the image to parse?
}
else
{
//do nothing
imgPicture.setImageBitmap(image);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
// show a message to the user indictating that the image is unavailable.
Toast.makeText(this, "Unable to open image", Toast.LENGTH_LONG).show();
}
}
}
}
You only can generate the bitmap from imageview but not in real image size, this generate the bitmap with imageview size
Bitmap bitmap;
try {
bitmap = Bitmap.createBitmap(YOUR_VIEW.getWidth(), YOUR_VIEW.getHeight(),
Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
YOUR_VIEW.draw(canvas);
File root = Environment.getExternalStoragePublicDirectory(Environment.PICTURES);
String fname = "NAME_OF_FILE.jpg";
file = new File(root, fname);
try {
if (!root.exists()) {
root.mkdir();
}
FileOutputStream out = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, out);
out.flush();
out.close();
YOUR_VIEW.destroyDrawingCache();
} catch (Exception e) {
e.printStackTrace();
}
} catch (Exception e) {
}
If you don't wanna save to a file, use this code:
public static Bitmap getScreenViewBitmap(View v) {
v.setDrawingCacheEnabled(true);
// this is the important code :)
// Without it the view will have a dimension of 0,0 and the bitmap will be null
v.measure(View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED),
View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED));
v.layout(0, 0, v.getMeasuredWidth(), v.getMeasuredHeight());
v.buildDrawingCache(true);
Bitmap b = Bitmap.createBitmap(v.getDrawingCache());
v.setDrawingCacheEnabled(false); // clear drawing cache
return b;
}
First of all im giving the codes what i'm using currently
MainActivity
static final String URL = "http://my .com/images/rss.xml";
static final String KEY_TITLE = "item";
static final String KEY_THUMB_URL = "thumb_url";
// Click event for single list row
gridView.setOnItemClickListener(new OnItemClickListener() {
#SuppressWarnings("unchecked")
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
HashMap<String, String> map2 = (HashMap<String, String>) parent.getItemAtPosition(position);
Intent in = new Intent(getApplicationContext(), FullSize.class);
Bitmap b; // your bitmap
in.putExtra(KEY_TITLE, map2.get(KEY_TITLE));
in.putExtra(KEY_THUMB_URL, KEY_THUMB_URL);
startActivity(in);
}
});
2nd Activity
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fullsize);
ImageView image = (ImageView) findViewById(R.id.fullsizeimg2);
TextView txtName = (TextView) findViewById(R.id.txt1);
Intent in = getIntent();
// Receiving the Data
String name = in.getStringExtra("item");
Bitmap bitmap =(Bitmap) in.getParcelableExtra("thumb_url");
// Displaying Received data
txtName.setText(name);
image.setImageBitmap(bitmap);
}
}
in this case, if i use the codes as above , the title works , i can see the text in txt but i cannot get img. i think i need to convert it to bitmap but also it didnt work for me. for converting bitmap i used this
Bitmap bitmap = BitmapFactory.decodeResource(getResources(),"Image ID");
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 40, bytes);
////////for intent /////
intent.putExtra("imagepass", bytes.toByteArray());
/////////2nd activity//////////
Bundle extras = getIntent().getExtras();
byte[] byteArray = extras.getByteArray("imagepass");
Bitmap bmp = BitmapFactory.decodeByteArray(byteArray, 0, byteArray.length);
ImageView iv=(ImageView) findViewById(R.id.fullsizeimg);
iv.setImageBitmap(bmp);
but in main activity after decoderesource line, it was giving this error :
The method decodeResource(Resources, int) in the type BitmapFactory is not applicable for the arguments (Resources, String)
I will be very happy if you can help.
You are using String as the second parameter in BitmapFactory.decodeResource()
But according to your code the Bitmap creation should be like this
Bitmap bMap = BitmapFactory.decodeResource(getResources(), R.drawable.yourImageId);