I'm using OpenGL ES to make a game in Android. I got some code from a tutorial and I'm trying to change it to suit my app but I'm having a problem. I want to dynamically get an image resource using a string passed into a function as the resource name. I know usually you use getIdentifier() in this case, but that returns an int and I need an input stream. Is there any way of getting an input stream from a resource dynamically?
Alternatively, is there a better way of doing this?
Code below:
InputStream is = mContext.getResources().openRawResource(R.drawable.<imagename>);
Bitmap bitmap;
try {
bitmap = BitmapFactory.decodeStream(is);
}
finally {
try {
is.close();
}
catch (IOException e) {
e.printStackTrace();
}
}
yes u can Suppose u have images stored in drawable with naming img1,img2,img3,img4,img5,img6,img7 than
first make an array like
String[] imgarray={"img1","img2","img3","img4","img5","img6","img7"};
public static String PACKAGE_NAME ;
PACKAGE_NAME=getApplicationContext().getPackageName();
Random r = new Random();
int n=r.nextInt(imgarray.length());
int resID = getResources().getIdentifier( PACKAGE_NAME+":drawable/" +imgarray[n] , null, null);
imageview.setImageResource(resID);
if want bitmap image than just add below line
Bitmap bm = BitmapFactory.decodeResource(getResources(),resID);
if u want other way with less coding than see accepted answer at Other Example
Related
I'm trying to make a simple Android app for my own phone that looks at my Gallery, and for each image/video file:
creates a Bitmap thumbnail of the file
records the file's absolute path on the phone
Essentially, I'll have the following data model:
public class MediaFileModel {
private Bitmap thumbnail;
private String absPath;
// ctor, getters and setters omitted for brevity
}
And I need something that looks at all the files in my Gallery and yields a List<MediaFileModel>. My best attempt is here:
public List<MediaFileModel> getAllGalleryMedia() {
String[] projection = { MediaStore.MediaColumns.DATA };
List<MediaFileModel> galleryMedia = new ArrayList<>();
Cursor cursor = getActivity().getContentResolver().query(
MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
projection,
null,
null,
null);
// I believe here I'm iterating over all the gallery files (???)
while(cursor.moveToNext()) {
MediaFileModel next = new MediaFileModel();
// is this how I get the abs path of the current file?!?
String absPath = cursor.getString(cursor.getColumnIndex(MediaStore.MediaColumns.DATA));
Bitmap thumbnail = null;
if (true /* ??? cursor is pointing to a media file that is an image/photo ??? */) {
thumbnail = ThumbnailUtils.extractThumbnail(BitmapFactory.decodeFile(absPath), 64, 64);
} else {
// else we have a video (I assume???)
thumbnail = ThumbnailUtils.createVideoThumbnail(absPath, MediaStore.Images.Thumbnails.MINI_KIND);
}
next.setThumbnail(thumbnail);
next.setAbsPath(absPath);
galleryMedia.add(next);
}
return galleryMedia;
}
However I'm not sure if my media query is setup correctly and I'm definitely not sure how to determine whether the file is an image/photo of a video, which I (believe I) need so that I can use the correct method for obtaining the thumbnail Bitmap.
Can anyone help nudge me over the finish line here?
Here is a code I was using for something similar, I hope this will help:
//The code has been removed
Note: Sorry I've removed the code because I am not sure if it has some portion copied from other open-sourced codes, I am using it in my apps but I can't remember if it is quoted from other source, so I've removed it, also it could be auto-completed using github copilot
I trying to create a custom photo gallery which the user can store Images from MediaStore photo gallery,
And my target is that the user can only the store different Image in database, if it is a duplicate Image it will not store .So , Im thinking hey, I can use the filepath as sort of A Id to check for duplicate Images. But evertime I restart the app and repick the same picture the Uri/filepath is not the same espicially the lastpart of the filePath/Uri
My Weird Implementation to Check duplicate:
public void checkAndSetPhotoGalleryData() throws IOException {
RoomDB db = RoomDB.getInstance(this);
PhotoGalleryData photoGalleryData = new PhotoGalleryData();
String stringUri = String.valueOf(imageUri);
String lastPartFile = stringUri.substring(stringUri.lastIndexOf('/')+1);
TextView testThis = findViewById(R.id.testName);
testThis.setText(db_path);
if(photoGarList.isEmpty()) {
try {
InputStream iStream = getContentResolver().openInputStream(imageUri);
byte[] inputData = getBytes(iStream);
photoGalleryData.setKey_Value_Quiz(String.valueOf(lastPartFile));
photoGalleryData.setPhoto(inputData);
db.questionDao().insert(photoGalleryData);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}if(!photoGarList.isEmpty())
{for(int i = 0; i<photoGarList.size();i++){
if (photoGarList.get(i).getKey_Value_Quiz().length() > 0 && !photoGarList.isEmpty() && photoGarList.get(i).getKey_Value_Quiz().equals(String.valueOf(lastPartFile))) {
showLongToast("Are Identical");
}
if (photoGarList.get(i).getKey_Value_Quiz().length() > 0 && !photoGarList.isEmpty() && !photoGarList.get(i).getKey_Value_Quiz().equals(String.valueOf(lastPartFile)) && i == photoGarList.size()-1) {
try {
InputStream iStream = getContentResolver().openInputStream(imageUri);
byte[] inputData = getBytes(iStream);
photoGalleryData.setKey_Value_Quiz(String.valueOf(lastPartFile));
photoGalleryData.setPhoto(inputData);
db.questionDao().insert(photoGalleryData);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}
}
}
lastPart of filePath:
///both of this are the same picture:
KeyValue:924270434
KeyValue:239256090
I guess that for security reason they change the last part every time, So I want to know is there any constant factor of a picture except for byte[] or Bitmap(Size is to Huge to store at once and this is not the case).
You could use simple pixel by pixel comparison of the images.
Try to use ImageMagic:
ImageMagic
Or you could try Java OpenCV: How to compare two images using Java OpenCV library
This question already has answers here:
Sharing Bitmap via Android Intent
(9 answers)
Closed 3 years ago.
People would like to know how I share an image generated within the app,
in the app's scope the person writing in the text view it captures and generates an image would like to share that image via whats or email.
private void gerarQRCode() {
String texto = edtTexto.getText().toString();
MultiFormatWriter multiFormatWriter = new MultiFormatWriter();
try {
BitMatrix bitmatrix = multiFormatWriter.encode(texto, BarcodeFormat.QR_CODE, 2000, 2000);
BarcodeEncoder barcodeEncoder = new BarcodeEncoder();
Bitmap bitmap = barcodeEncoder.createBitmap(bitmatrix);
ivQRCode.setImageBitmap(bitmap);
} catch (WriterException e) {
e.printStackTrace();
}
}
Step #1: Write the Bitmap to a file on internal storage, using the compress() method
Step #2: Set up FileProvider to be able to serve files from where you are storing the bitmap
Step #3: Use FileProvider.getUriForFile() to get a Uri representing that bitmap
Step #4: Use ACTION_SEND to offer that bitmap to other apps for sharing purposes
I want to get image dpi to convert pixels to cm, so I use ImageInfo.java to get this:
ImageInfo myMapInfo = new ImageInfo();
try {
File testFile = new File(fileNameString);
InputStream myMapStream = new FileInputStream(testFile);
myMapInfo.setInput(myMapStream);
myMapInfo.setDetermineImageNumber(true);
myMapInfo.setCollectComments(true);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
x = myMapInfo.getPhysicalWidthInch();
y = myMapInfo.getPhysicalHeightInch();
but unfortunately I get -1 and -1 in (x, y)! I use this class:
ImageInfo.java
From looking at the source code of ImageInfo, you need to call the check() method of your myMapInfo variable and if this passes you can use the various getXxX() methods to obtain whatever information you need. Incidentally getting -1 as result means information is not available, but that's most likely cause you're not invoking the check() method.
Right now I am creating thumbnail using below method-
Bitmap thumb = ThumbnailUtils.createVideoThumbnail(path,
MediaStore.Images.Thumbnails.MICRO_KIND);
This method is working fine, The problem is I am getting thumbnail from the beginning of the video (Might be from 00:00 or 00:01).
My Ques is, Can I get Thumbnail from specified position(Let's say 00:05)?
Thanks.
Yes you can by below way..
MediaMetadataRetriever retriever = new MediaMetadataRetriever();
try {
retriever.setDataSource(filePath);
//here 5 means frame at the 5th sec.
bitmap = retriever.getFrameAtTime(5);
} catch (Exception ex) {
// Assume this is a corrupt video file
}
For more info check it MediaMetadataRetriever
FFmpegMediaMetadataRetriever will accomplish what you want and it works with API 7+:
FFmpegMediaMetadataRetriever retriever = new FFmpegMediaMetadataRetriever();
try {
retriever.setDataSource(filePath);
//here 5 means frame at the 5th sec.
bitmap = retriever.getFrameAtTime(5);
} catch (Exception ex) {
// Assume this is a corrupt video file
}