I'm trying to display ImageView using Bitmap and Bitmap get it's value from sharedpref path
/// Activity Fields
ٍString mWinPhotoPath, mLosePhotoPath;
ImageView winnerImage, loserImage;
Bitmap winImage, loseImage;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_winner);
//// Get shared pref values
mWinPhotoPath = **sharedPreferences.getString(getString(R.string.sharedPreferences_winner_pic), getString(R.string.error_sorry_message)); // win pic
mLosePhotoPath = sharedPreferences.getString(getString(R.string.sharedPreferences_loser_pic), getString(R.string.error_sorry_message)); // lose pic**
**winImage = BitmapFactory.decodeFile(mWinPhotoPath);
loseImage = BitmapFactory.decodeFile(mLosePhotoPath);**
// Activity Objects
**winnerImage = findViewById(R.id.winner_image);**
**loserImage = findViewById(R.id.loser_image);**
// set values
**winnerImage.setImageBitmap(winImage);**
**loserImage.setImageBitmap(loseImage);**
I don't have any error in my log but the problem is the ImageView didn't display Bitmap
also I checked that the shared pref get the path value correctly
Is there any logical error in my code !!?
What's the problem ?
To get bitmap from a path you need to use this code below
File image = new File(mWinPhotoPath, imageName);
BitmapFactory.Options bmOptions = new BitmapFactory.Options();
Bitmap bitmap = BitmapFactory.decodeFile(image.getAbsolutePath(),bmOptions);
winImage = Bitmap.createScaledBitmap(bitmap,parent.getWidth(),parent.getHeight(),true);
If you are storing path of file in SharedPrefrence then you can decode file into bitmap by using its path.
File f = new File(file path....);
Bitmap map = BitmapFactory.decodeFile(f.getAbsolutePath());
image.setImageBitmap(map);
OR
String fileName = "...."; // file path
File completeFile = new File(fileName);
FileInputStream readPicture = new FileInputStream(completeFile);
BufferedInputStream bf = new BufferedInputStream(readPicture);
Bitmap bitmap = BitmapFactory.decodeStream(bf);
Related
I'm trying to use an Activity which displays a random object from my array. This object is passed in from an intent.
I am trying to use an image for each of these objects and then display the correct image for the correct object.
So far I've been using the drawable folder to hold my images and then loading them in through the XML however this stops me using multiple images for the same ImageView.
I tried using imageview.setImageResource(R.drawable.imagename); but that doesn't seem to like loading in for some reason.
Do I need to make a new activity for each of the objects in this case?
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_random_race);
TextView name = (TextView)findViewById(R.id.raceName);
Intent secondIntent = getIntent();
Race message = (Race)secondIntent.getSerializableExtra("RACE");
ImageView image = (ImageView) findViewById(R.id.raceImage);
image.setImageResource(R.drawable.hacan);
image.setImageBitmap(imageToBitmapImage(message, image));
name.setText(message.getName());
}
Bytes to Bitmap method
public Bitmap imageToBitmapImage (Race message, ImageView image){
Bitmap bmp;
try {
FileInputStream in = new FileInputStream(message.getImageName());
BufferedInputStream buffer = new BufferedInputStream(in);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
int input = buffer.read();
while (input != -1){
baos.write(input);
input = buffer.read();
}
byte[] bytes = baos.toByteArray();
bmp = BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
return bmp;
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
Class of each object I'm talking about.
public class Race implements Serializable {
private String name;
private String imageName; //name of file within drawable
As #XavierFalempin commented, you can't access ressources through a file stream. Using setImageResource() should work. Following this answer your onCreate() method should look something like this:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_random_race);
TextView name = (TextView)findViewById(R.id.raceName);
Intent secondIntent = getIntent();
Race message = (Race)secondIntent.getSerializableExtra("RACE");
ImageView image = (ImageView) findViewById(R.id.raceImage);
image.setImageResource(getResources().getIdentifier(message.getImageName(),
"drawable",
getPackageName()));
name.setText(message.getName());
}
So I have a database with a table where a User name corresponds to the name of an image. So In my AsyncHTTP I retrieve the Username and wish to map that Username to its correct image(all images are located in my drawable folder)
In my XML where this image will be rendered I just put an imageview and never assigned it an image(the Id for this imageView is myImage)
So how when I run my code the image is not rendered. I cant assign the image outside of async because of scope issues.
Context context = this;
AsyncHTTPPost asyncHttpPost2 = new AsyncHTTPPost(
"http://lamp.ms.wits.ac.za/~s1363679/avatars.php", params) {
#Override
protected void onPostExecute(String s) {
try {
JSONArray all = new JSONArray(s);
for (int i = 0; i < all.length(); i++) {
JSONObject item = all.getJSONObject(i);
fName = item.getString("avatarName");
System.out.println();
Toast.makeText(Profile.this, fName, Toast.LENGTH_LONG).show();
ImageView Image = (ImageView) findViewById(R.id.myImage);
System.out.println("");
theName = fName;
//String imagename="kaius";
Resources res = context.getResources();
int resID = res.getIdentifier(theName, "drawable", context.getPackageName());
Image.setImageResource(resID);
}
} catch (Exception e) {
Toast.makeText(Profile.this, e.toString(), Toast.LENGTH_LONG).show();
}
}
};
asyncHttpPost2.execute();
}
The imageName is retrieved correctly and stored in the variable "theName" but it doesnt seem to render onto the view.
At the same level of your drawable folder, there should also be some folders with these names:
-drawable-hdpi
-drawable-xhdpi
-drawable-xxhdpi
-drawable-xxxhdpi
Your images should be scaled according to different dpi´s and placed inside those folders to render correctly in all screens.
Another thing you could do instead, is:
// get drawable path
String imageUri = "drawable://" + R.drawable.image;
imageView.setImageBitmap(decodeSampledBitmapFromFile(imageUri , 1920, 1080));
And declare somewhere decodeSampledBitmapFromFile like this:
public static Bitmap decodeSampledBitmapFromFile(String imagePath,
int reqWidth, int reqHeight) {
// BitmapFactory.decodeFile(this.getFilesDir().getPath() + "/" + imagestoplay[currImage])
// First decode with inJustDecodeBounds=true to check dimensions
final BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
// BitmapFactory.decodeResource(res, resId, options);
BitmapFactory.decodeFile(imagePath, options);
// Calculate inSampleSize
options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);
// Decode bitmap with inSampleSize set
options.inJustDecodeBounds = false;
return BitmapFactory.decodeFile(imagePath, options);
}
Don´t forget to change 1080 and 1920 to your required size in pixels.
I am trying to use RenderScript to create a blurred bitmap to set it as a background for a LinearLayout which contains an ImageView. I also want a clear original copy of the bitmap so that I can set it as an image in the ImageView.
Here's my code:
ImageView mainImage;
Bitmap mainBMP, blurredBMP
LinearLayout background;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_work_area);
getImage(); // obtain bitmap from file
mainImage.setImageBitmap(mainBMP); // set the original bitmap in imageview
// create a blurred bitmap drawable and set it as background for linearlayout
BitmapDrawable drawable = new BitmapDrawable(getResources(), blur(mainBMP));
mainBackground.setBackground(drawable);
registerForContextMenu(objectImage);
registerForContextMenu(textArea);
}
private void getImage(){
String filename = getIntent().getStringExtra("image");
try {
FileInputStream is = this.openFileInput(filename);
mainBMP = BitmapFactory.decodeStream(is);
is.close();
} catch (Exception e) {
e.printStackTrace();
}
}
#TargetApi(17)
public Bitmap blur(Bitmap image) {
if (null == image) return null;
Bitmap outputBitmap = Bitmap.createBitmap(image);
final RenderScript renderScript = RenderScript.create(this);
Allocation tmpIn = Allocation.createFromBitmap(renderScript, image);
Allocation tmpOut = Allocation.createFromBitmap(renderScript, outputBitmap);
//Intrinsic Gausian blur filter
ScriptIntrinsicBlur theIntrinsic = ScriptIntrinsicBlur.create(renderScript, Element.U8_4(renderScript));
theIntrinsic.setRadius(BLUR_RADIUS);
theIntrinsic.setInput(tmpIn);
theIntrinsic.forEach(tmpOut);
tmpOut.copyTo(outputBitmap);
return outputBitmap;
}
This is how I want the final result to be:
But this is what I get:
So how do I make two copies of the same bitmap in which one of them is blurred and the other is clear and original?
The problem is with how the output bitmap is being created. You're using a call that gives you an immutable Bitmap object based on an input Bitmap object. Change this line:
Bitmap outputBitmap = Bitmap.createBitmap(image);
to be this:
Bitmap outputBitmap = image.copy(image.getConfig(), true);
That will give you a separate Bitmap object which is a copy of the original and mutable. Right now Renderscript is really modifying the original (though it really should fail because the outputBitmap was immutable.
I have a particular scenario, I'm very close to finishing! Basically, I've got some decodeBase64 strings in a database that need to be used in a BitmapFactory and then drawn.
public static Bitmap decodeBase64(String input)
{
byte[] decodedByte = Base64.decode(input, 0);
return BitmapFactory.decodeByteArray(decodedByte, 0, decodedByte.length);
}
Here is my MainActivity.java:
// Initiate Database
DatabaseHandler db = new DatabaseHandler(this); // "this" refer to the context
// Grab current Car for use.
Car cars = db.getCurrentCar();
// Grab String from database and decode to Base64
//ByteConvert.decodeBase64(cars.get_image());
// Create Bitmap object from database source
BitmapFactory(ByteConvert.decodeBase64(cars.get_image());
// Draw image from string
Drawable draw = new BitmapDrawable(getResources(), BITMAPFACTORY GOES HERE);
// Set R.id.DRAWABLE to imageView
My question, is how do I turn this string I'm returning from decodeBase64 into a BitmapFactory and then Draw it?
I have done my best to try and fill out how I think it works.
Thanks
The Base64.decode method is returning a byte array, so you can use BitmapFactory's decodeByteArray method to build your bitmap, and set it on your ImageView.
Ex:
DatabaseHandler db = new DatabaseHandler(this);
Car cars = db.getCurrentCar();
byte[] imageData = Base64.decode(cars.get_image(), 0);
Bitmap bitmap = BitmapFactory.decodeByteArray(imageData, 0, imageData.length, new BitmapFactory.Options());
ImageView imageView = //find your image view;
imageView.setImageBitmap(bitmap);
Hi i have a string in Base64 format. I want to convert it ot a bitmap and then display it to an ImageView. This is the code:
ImageView user_image;
Person person_object;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.user_profile_screen);
// ImageViews
user_image = (ImageView) findViewById(R.id.userImageProfile);
Bundle data = getIntent().getExtras();
person_object = data.getParcelable("person_object");
// getPhoto() function returns a Base64 String
byte[] decodedString = Base64.decode(person_object.getPhoto(), Base64.DEFAULT);
Bitmap decodedByte = BitmapFactory.decodeByteArray(decodedString, 0, decodedString.length);
user_image.setImageBitmap(decodedByte);
}
This code get the Base64 String successfully and i do not get any error. But It does not display the image.
What can be the problem?
Thanks
Please try this:
byte[] decodedString = Base64.decode(person_object.getPhoto(),Base64.NO_WRAP);
InputStream inputStream = new ByteArrayInputStream(decodedString);
Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
user_image.setImageBitmap(bitmap);
//decode base64 string to image
imageBytes = Base64.decode(encodedImage, Base64.DEFAULT);
Bitmap decodedImage = BitmapFactory.decodeByteArray(imageBytes, 0, imageBytes.length);
image.setImageBitmap(decodedImage);
//setImageBitmap is imp
There is a library named Picasso which can efficiently load images from a URL. It can also load an image from a file.
Examples:
Load URL into ImageView without generating a bitmap:
Picasso.with(context) // Context
.load("http://abc.imgur.com/gxsg.png") // URL or file
.into(imageView); // An ImageView object to show the loaded image
Load URL into ImageView by generating a bitmap:
Picasso.with(this)
.load(artistImageUrl)
.into(new Target() {
#Override
public void onBitmapLoaded(final Bitmap bitmap, Picasso.LoadedFrom from) {
/* Save the bitmap or do something with it here */
// Set it in the ImageView
theView.setImageBitmap(bitmap)
}
#Override
public void onBitmapFailed(Drawable errorDrawable) {
}
#Override
public void onPrepareLoad(Drawable placeHolderDrawable) {
}
});
There are many more options available in Picasso. Here is the documentation.
this code works with me
ImageView carView = (ImageView) v.findViewById(R.id.car_icon);
byte[] decodedString = Base64.decode(picture, Base64.NO_WRAP);
InputStream input=new ByteArrayInputStream(decodedString);
Bitmap ext_pic = BitmapFactory.decodeStream(input);
carView.setImageBitmap(ext_pic);