Relative path using setImageResource - java

I am trying to display an image in my app that changes everytime I press a button.
The name of the image that should be shown is in my object. I can get the name of the image with
String nameOfImage = myObhect.get(i).getImageName();
Now, I want to display the current image with
iv.setImageResource(R.drawable.notruf);
Using setImageResource , I don´t know how to bring the name of my image in setImageResource because, for example
iv.setImageResource(R.drawable. + aktbild) isn´t possible for sure.
I also tried the way with setImageDrawable but that does not work for me.

I use similar solution in my application :
Context mContext = this; // I supposed you're in Activity
String imgName = fragenkatalog.get(i).getBild();
int resId = mContext.getResources().getIdentifier(imgName,
"drawable", mContext.getApplicationInfo().packageName);
if(resId > 0){
iv.setImageResource(resId);
}

I believe that this code will help u..
String aktbild = fragenkatalog.get(i).getBild();
byte[] decodedString = Base64.decode(aktbild , Base64.DEFAULT);
Bitmap decodedByte = BitmapFactory.decodeByteArray(decodedString, 0,
decodedString.length);
After that, if you want to resize that image use this code.
int width=75;
int height=75;
Bitmap resizedbitmap=Bitmap.createScaledBitmap(decodedByte, width, height, true);
finally set image into ImageView.
Icon.setImageBitmap(resizedbitmap);`

Related

Loading a bitmap with ImageDecoder from URI and adding text

In my activity, I want to modify an image to add a text on it.
The image is selected in the galery or taken with the camera and then stored in a file in a previous activity. Then the uri of that file is passed through extras.
Now I try to add a string on top of the image like so:
try {
modifyThePic(imageUri);
} catch (IOException e) {
e.printStackTrace();
}
here is the function's body:
public void modifyThePic(Uri imageUri) throws IOException {
ImageDecoder.Source source = ImageDecoder.createSource(this.getContentResolver(), imageUri);
Bitmap bitmap = ImageDecoder.decodeBitmap(source);
Canvas canvas = new Canvas(bitmap);
Paint paint = new Paint();
paint.setColor(Color.BLACK);
paint.setTextSize(10);
canvas.drawText("Some Text here", 0, 0, paint);
image.setImageBitmap(bitmap); //image is the imageView to control the result
}
The expected behaviour would be to display the image with "Some Text here" on top of it. But instead there is nothing displayed, however the app doesn't crash.
While debugging, I come across an error that appears between the
Bitmap bitmap = ImageDecoder.decodeBitmap(source);
and the
Canvas canvas = new Canvas(bitmap);
here is the error:
java.io.FileNotFoundException: No content provider: /storage/emulated/0/Android/data/com.emergence.pantherapp/files/Pictures/JPEG_20200829_181926_7510981182141824841.jpg
I suspect that I missuse the "ImageDecoder" as it's my first time using it. More precisely, I was not able to let the "decodeBitmap" method in onCreate, Android Studio was telling me that it could not be in the "main thread", I am not familiar at all with threading. Moving it in a dedicaded function fixed this but maybe am I supposed to do something else and it's the root of the problem.
My questions:
Am I using the right tools to modify the file and add the text on it ?
If yes, what do I do wrong ?
If no, what library/tools should I look into to do this task ?
Thank you,
EDIT: ADDITONAL ANSWER ELEMENTS
As both #blackapps and #rmunge pointed out, I was not getting a legit URI but instead a file path. The easy fix for my problem was to get the URI from the path using this code:
Uri realuri = Uri.fromFile(new File("insert path here")));
Additionaly to edit the bitmap, it must be made mutable which is covered here for example.
The final function to extract the bitmap from the URI and adding text on top of it is this one:
public void modifyThePic(Uri imageUri) throws IOException {
ContentResolver cr = this.getContentResolver();
InputStream input = cr.openInputStream(imageUri);
Bitmap bitmap = BitmapFactory.decodeStream(input).copy(Bitmap.Config.ARGB_8888,true);
Canvas canvas = new Canvas(bitmap);
Paint paint = new Paint();
paint.setColor(Color.BLACK);
paint.setTextSize(300);
int xPos = (canvas.getWidth() / 2); //just some operations to center the text
int yPos = (int) ((canvas.getHeight() / 2) - ((paint.descent() + paint.ascent()) / 2)) ;
canvas.drawText("SOME TEXT TO TRY IT OUT", xPos, yPos, paint);
image.setImageBitmap(bitmap);
}
Seems your URI is wrong. It has to start with file:///

Android : FileNotFoundException when trying to get an image from Uri

I am trying to get an image's width and height in order to rezize it in case it is too big before showing it. My method receive an uri of the image but I always get a FileNotFoundException when trying to decode it using BitmapFactory.
Here is a sample of my code :
Uri myUri;
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeFile(new File(myUri.getPath()).getAbsolutePath(), options);
int imageHeight = options.outHeight;
int imageWidth = options.outWidth;
Decode File returns throws a FileNotFoundException here. However, I can still show the image using the uri without using a bitmap factory using this :
Uri myUri;
Bitmap myBitmap = MediaStore.Images.Media.getBitmap(context.getContentResolver(), myUri);
The problem with this code is that the returned bitmap might cause an OutofMemoryError when using big images.
When I debug my Uri, I get this :
content://com.android.providers.media.documents/document/image%3A20472
UPDATE || Here is the working code
Uri myUri;
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
// This is the part that changed
InputStream inputStream = context.getApplicationContext().getContentResolver().openInputStream(myUri);
BitmapFactory.decodeStream(inputStream,new Rect(),options);
int imageHeight = options.outHeight;
int imageWidth = options.outWidth;
All of this of course surrounded by try/catch.
Use decodeStream instead of decodeFile.
Open the stream with getContentResolver().openInputStream(myUri).
After playing around with this for a while, I think the issue is probably that the image file really isn't there.
If you are attempting to access a local file on your computer, that file won't be in the Android sandbox where the app is actually running. You'll need to add it to the app as a resource, then access it as a resource instead of a file.
If you are attempting to access a web image, you need to download it first. The AbsolutePath of a web image 'http://example.com/example.jpg' would be '/example.jpg', which won't do you much good when you try to open it.

codename one image from url

I am trying to make a mobile app using Java and codename one plugin. My question is - what's the simples way to populate an image from a URL to a label? I Googled it and all I found was this piece of code:
Image i = URLImage.createToStorage(placeholder, "fileNameInStorage", "http://xxx/myurl.jpg", URLImage.RESIZE_SCALE);
But I have no idea how to use it. What is a placeholder? It asks an EncodedImage parameter, but if I do:
EncodedImage image = new EncodedImage(10, 10);
I get the error that EncodedImage is protected.
I simply want to populate an image from a URL to my desired label in a form.
I am using GUI builder.
The placeholder image is the image that should show while the image from URL is being downloaded and it's an EncodedImage.
If your Label already have an icon as a placeholder, you can use its icon, otherwise you can create a new placeholder image. Below are 3 options to create an EncodedImage and a URLImage usage example:
Method 1:
//generate a grey placeholder that matches the size of the label's icon
Image placeholder = Image.createImage(label.getIcon().getWidth(), label.getIcon().getWidth(), 0xbfc9d2);
EncodedImage encImage = EncodedImage.createFromImage(placeholder, false);
Method 2:
//Convert the label icon to EncodedImage
EncodedImage encImage = (EncodedImage)label.getIcon();
Method 3:
//Create a fresh grey EncodedImage when label doesn't have any icon set initially
int deviceWidth = Display.getInstance().getDisplayWidth();
Image placeholder = Image.createImage(deviceWidth / 10, deviceWidth / 10, 0xbfc9d2); //square image set to 10% of screen width
EncodedImage encImage = EncodedImage.createFromImage(placeholder, false);
Usage Example:
It's a good practice to use the URL as the cached image name in storage. If you have a multiple sizes of the same image, just prefix them with a unique string like "Large" + URL
label.setIcon(URLImage.createToStorage(encImage, "Medium_" + "http://xxx/myurl.jpg", "http://xxx/myurl.jpg", URLImage.RESIZE_SCALE));

Generate a image with custom text in Android

I'm trying to make an app for create custom cards. I'd like to add some text over a custom background (a jpg image).
What is the best way of doing it? I'd need to show the user a preview of the card before send it to the server.
Thanks
Use below code to achieve your requirement
Bitmap src = BitmapFactory.decodeResource(getResources(), R.drawable.yourimage); // the original file yourimage.jpg i added in resources
Bitmap dest = Bitmap.createBitmap(src.getWidth(), src.getHeight(), Bitmap.Config.ARGB_8888);
String yourText = "My custom Text adding to Image";
Canvas cs = new Canvas(dest);
Paint tPaint = new Paint();
tPaint.setTextSize(35);
tPaint.setColor(Color.BLUE);
tPaint.setStyle(Style.FILL);
cs.drawBitmap(src, 0f, 0f, null);
float height = tPaint.measureText("yY");
float width = tPaint.measureText(yourText);
float x_coord = (src.getWidth() - width)/2;
cs.drawText(yourText, x_coord, height+15f, tPaint); // 15f is to put space between top edge and the text, if you want to change it, you can
try {
dest.compress(Bitmap.CompressFormat.JPEG, 100, new FileOutputStream(new File("/sdcard/ImageAfterAddingText.jpg")));
// dest is Bitmap, if you want to preview the final image, you can display it on screen also before saving
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
You have to use below permission in manifest file.
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
For my device the path is /sdcard to access external SD card, it may vary for other devices. Some devices may have /mnt/sdcard may be it is for internal sd cards. Just check it while before using this code.
Actually I wrote the above code for some other question, which required time stamp on photo after captured from camera. I gave you the same solution with a little modifications for your specific requirement.
I hope you can understand this. If you have any doubts regarding code feel free to ask.
I am not sure this is the best solution, but it might help you.
Step1: Create a relative layout (or any other layout) and set your image as its background.
Step2: Now add a TextView with width and height as match_parent and gravity set as top|center_horizontal.
Step3: Now add another button or any other layout control which will trigger the user confirmation. (You should place this control outside the Relative layout).
Step4: If user has confirmed the image then you can take screenshot of your relative layout via following code:
v1.setDrawingCacheEnabled(true); //v1 is the object of your Relative layout
Bitmap bm = v1.getDrawingCache();
if (bm != null) {
//TODO: write the code for saving the image.
Toast toast = Toast.makeText(YourActivity.this, "image saved",
Toast.LENGTH_LONG);
toast.show();
} else {
Toast toast = Toast.makeText(YourActivity.this,
"No image saved.", Toast.LENGTH_LONG);
toast.show();
}

Display jpg from sdcard android

I cant get this to work anymore
Here is my code:
ImageView jpgView = (ImageView)findViewById(R.id.ImageView01);
String myJpgPath = "/sdcard/pic.jpg";
jpgView.setVisibility(View.VISIBLE);
//jpgView.setScaleType(ImageView.ScaleType.FIT_CENTER);
jpgView.setAdjustViewBounds(true);
BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = 2;
Bitmap bm = BitmapFactory.decodeFile(myJpgPath, options);
jpgView.setImageBitmap(bm);
Can anyone help?
You can just use bitmapdrawable, e.g.
ImageView jpgView = (ImageView)findViewById(R.id.ImageView01);
String myJpgPath = "/sdcard/pic.jpg";
BitmapDrawable d = new BitmapDrawable(getResources(), myJpgPath);
jpgView.setImageDrawable(d);
The image won't be shown if you open the emulator directly from the eclipse, by clicking run. You'll be able to access the SD card if you start the emulator using the command line, then click your app on the emulator.

Categories