I want to add images from asses to an imageview automatically. the below code does work well when images are in a drawable folder, but I want to create a separate folder name avatar in the asset folder and get random images from there in my imageview.
int[] images = new int[] {R.drawable.image01, R.drawable.image02, R.drawable.image03};
// Get the ImageView
setContent(R.layout.main);
ImageView mImageView = (ImageView)findViewById(R.id.myImageView);
// Get a random between 0 and images.length-1
int imageId = (int)(Math.random() * images.length);
// Set the image
mImageView.setBackgroundResource(images[imageId]);
Thanks in advance.
I suggest you to use AssetManager.list()
To list all the assets for the given folder within /assets folder, we use AssetManager.list(). Suppose we have some files within /assets/img and we need to list all those files, then we write code as follows.
String[] imgPath = assetManager.list("img");
Here we get String array of file names within img directory.
try {
String[] imgPath = assetManager.list("img");
for (int i = 0; i< imgPath.length; i++) {
InputStream is = assetManager.open("img/"+imgPath[i]);
Log.d(TAG, imgPath[i]);
Bitmap bitmap = BitmapFactory.decodeStream(is);
imageViewbyCode = new ImageView(this);
imageViewbyCode.setImageBitmap(bitmap);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
imageViewbyCode.setLayoutParams(params);
myLayout.addView(imageViewbyCode);
}
} catch (IOException e) {
Log.e(TAG, e.getMessage());
}
Please try below code:-
AssetManager assetManager = getAssets();
ImageView mImageView = (ImageView)findViewById(R.id.myImageView);
InputStream inputStream = assetManager.open("yourimage.jpg")
Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
mImageView.setImageBitmap(bitmap);
Related
I' making an android app which allows the user to take a photo and then the app will print some RGB value etc. I'm saving the pictures taken on the phone and then I make a bitmap out of those png files. I just found out that I should sleep the application for a moment in order for the image to be saved. But I'm still getting that the bitmap is null for some images I take. If I take an image of Rubik's cube with it's 6 different colors I almost never get the null pointer exception. But if I take a picture of the wall or something else the bitmap is = null.
Does anyone know what I should do in order to fix this?
Bitmap myBitmap;
final String dir =
Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES) +
"/picFolder/";
try{
file = dir+Integer.toString(side)+".jpg";
File f = new File(file);
options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
options.inPreferredConfig = Bitmap.Config.ARGB_8888;
myBitmap = BitmapFactory.decodeFile(file,options);
for(int i = 0; i<3; i++){
for(int j = 0; j<3; j++){
cube[side-1][i][j] = getColor(myBitmap, i, j);
}
}
}catch (Exception e){
Log.e("er0r", "HERE:::: " + e.toString());
}
I also faced the same problem when I was developing camera in my app.
For some images it was working fine and for some images it was showing null.
Later I found that is a size issue.
I fixed that issue like this,
private static Bitmap compressBitmap(Bitmap original) {
ByteArrayOutputStream out = new ByteArrayOutputStream();
original.compress(Bitmap.CompressFormat.JPEG, 100, out);
Bitmap decoded = BitmapFactory.decodeStream(new ByteArrayInputStream(out.toByteArray()));
return decoded;
}
Let me know if you need any other help.
I am trying to capture one of my layout but getting black border in screenshot like below. How can I remove it ?
My code for taking screenshot is like below
private void takeScreenshot() {
Date now = new Date();
android.text.format.DateFormat.format("yyyy-MM-dd_hh:mm:ss", now);
try {
// image naming and path to include sd card appending name you choose for file
String mPath = Environment.getExternalStorageDirectory().toString() + "/" + now + ".jpg";
// create bitmap screen capture
View v1= findViewById(R.id.quoteViewPager);
v1.getRootView();
v1.setDrawingCacheEnabled(true);
Bitmap bitmap = Bitmap.createBitmap(v1.getDrawingCache());
v1.setDrawingCacheEnabled(false);
File imageFile = new File(mPath);
FileOutputStream outputStream = new FileOutputStream(imageFile);
int quality = 100;
bitmap.compress(Bitmap.CompressFormat.JPEG, quality, outputStream);
outputStream.flush();
outputStream.close();
openScreenshot(imageFile);
} catch (Throwable e) {
// Several error may come out with file handling or OOM
e.printStackTrace();
}
}
Thanks
Actually, I didn't get your code,
View v1= findViewById(R.id.quoteViewPager);
v1.getRootView();
it should be :
v1 = v1.getRootView();
Hope it will help you :)
How can I using Cursor get image and video thumbnails in my direct path in same cursor?
I need get the image and video thumbnails in /DCIM/100ANDRO folder.
But I just can separate to get image and video in at sd card all data.
private ArrayList<ImageItem> getData() {
final ArrayList<ImageItem> imageItems = new ArrayList<>();
ContentResolver cr = mContext.getContentResolver();
String[] projection = {MediaStore.Images.Thumbnails.DATA, MediaStore.Video.Thumbnails.DATA};
Cursor cursor = cr.query(MediaStore.Images.Thumbnails.EXTERNAL_CONTENT_URI,projection,null,null,null);
for( int i = 0 ; i < cursor.getCount(); i++)
{
cursor.moveToPosition(i);
String filePath = cursor.getString(cursor.getColumnIndex(MediaStore.Images.Thumbnails.DATA));
Log.i("info","filePath:"+filePath);
File file = new File(filePath);
Bitmap myBitmap = BitmapFactory.decodeFile(file.getAbsolutePath());
imageItems.add( new ImageItem(myBitmap, "Image#" + i) );
}
cursor = cr.query(MediaStore.Video.Thumbnails.EXTERNAL_CONTENT_URI,projection,null,null,null);
for( int i = 0 ; i < cursor.getCount(); i++)
{
cursor.moveToPosition(i);
String filePath = cursor.getString(cursor.getColumnIndex(MediaStore.Video.Thumbnails.DATA));
Log.i("info","filePath:"+filePath);
File file = new File(filePath);
Bitmap myBitmap = BitmapFactory.decodeFile(file.getAbsolutePath());
imageItems.add( new ImageItem(myBitmap, "Image#" + i) );
}
cursor.close();
return imageItems;
}
Have possible using cursor direct folder to get the thumbnails and get video and image thumbnails both?
thank you very much.
I found the answer.
We should inverse the method.
We can find the real path. then to get the ID.
Through the ID to get the images and videos thumbnails.
To get the images and videos using a cursor can refer the articles.
Getting images thumbnails using below code:
bitmap = MediaStore.Images.Thumbnails.getThumbnail(context
.getApplicationContext().getContentResolver(), item.getImgId(),
MediaStore.Images.Thumbnails.MICRO_KIND, null);
Getting video thumbnails using below code:
bitmap = MediaStore.Video.Thumbnails.getThumbnail(context
.getApplicationContext().getContentResolver(), item.getImgId(),
MediaStore.Images.Thumbnails.MICRO_KIND, null);
I have a specific problem which has not be answered yet on stackoverflow; I have images in the assets folder numbered like 0.jpg, 1.jpg, 2.jpg etc. Using a for loop I select three images from the asssets folder and I am trying to add these images to a gridview but the images are not showing. The activity starts up okay just no images!
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_result);
gridView = (GridView) findViewById(R.id.gridview_result);
// Sets the Tag
gridView.setTag(GRIDVIEW_TAG);
/*
* Adapt the image for the GridView format
*/
imageAdapter = new ImageGridViewAdapter(getApplicationContext());
gridView.setAdapter(imageAdapter);
// Set the orientation to landscape
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
// Retrieve 3 images form the database which appear
// similar
for (int i = 0; i < 3; i++) {
// System.out.println(Retrieval.distances[i][0]);
image = Retrieval.distances[i][0];
int num = (int) image;
StringBuilder sBuilder = new StringBuilder();
sBuilder.append(num);
String imageNum = sBuilder.toString();
System.out.println(imageNum);
String file = imageNum + ".jpg";
try {
// get input stream
InputStream ims = getAssets().open(file);
Log.i("ERROR_IMS", ims + "");
// load image as Drawable
Drawable d = Drawable.createFromStream(ims, file);
// set image to ImageView
gridView.setBackground(d);
Log.i("ERROR_d", d + "");
Log.i("ERROR_gridview", gridView+"");
} catch (IOException ex) {
Log.e("I/O ERROR", "Failed when ...");
}
}
}
I believe the issue is occurring in the try/catch. Any help will be much appreciated!
You should get all images first and set it to your adapter.
// set image to ImageView
gridView.setBackground(d);
doesn't affect to your grid items view.
A good tutorial for it: guide
I am using Universal-Image-Loader and there is this functionality that access the file cache of the image from sd card. But I don't know how to convert the returned file cache into bitmap. Basically I just wanted to assign the bitmap to an ImageView.
File mSaveBit = imageLoader.getDiscCache().get(easyPuzzle);
Log.d("#ImageValue: ", ""+mSaveBit.toString());
mImageView.setImageBitmap(mSaveBit);
Error: "The method setImageBitmap(Bitmap) in the type ImageView is not applicable for the arguments (File)"
You should be able to use BitmapFactory:
File mSaveBit; // Your image file
String filePath = mSaveBit.getPath();
Bitmap bitmap = BitmapFactory.decodeFile(filePath);
mImageView.setImageBitmap(bitmap);
Define File
String fileName = "/myImage.jpg";
File file = new File(fileName);
get Bitmap of Image
Bitmap bitmap = BitmapFactory.decodeFile(file.getAbsolutePath());
Set Bitmap to ImageView
myImageView.setImageBitmap(bitmap);
You can use this function to get Bitmap from file path
fun getBitmap(filePath:String):Bitmap?{
var bitmap:Bitmap?=null
try{
var f:File = File(path)
var options = BitmapFactory.Options()
options.inPreferredConfig = Bitmap.Config.ARGB_8888
bitmap = BitmapFactory.decodeStream(FileInputStream(f),null,options)
}catch (e:Exception){
}
return bitmap
}
Here is a simple code to create a scaled image for ImageView in this case
- Width:400
- Height:400
final File file = new File(Environment.getExternalStorageDirectory(),"b.jpg");
ImageView img = (ImageView) findViewById(R.id.imageview);
img.setImageBitmap(Bitmap.createScaledBitmap(BitmapFactory.decodeFile(file.getAbsolutePath()),400,400,false));
Kotlin Version
if (requestCode==PICK_IMAGE_REQUEST){
if (data!=null){
selectedfileUri=data.data
if (selectedfileUri!=null && !selectedfileUri!!.path.isEmpty()){
val file = FileUtils.getFile(context,selectedfileUri)
val bitmap = BitmapFactory.decodeFile(file.path)
uimg!!.setImageBitmap(bitmap)
}
}
}
This is not the right question, but if you use flag .cacheInMemory() in ImageLoader setup you can retrive the bitmap without need of recreate at any time using BitmapFactory to safe memory usage .
Just use:
Bitmap bitmap = ImageLoader.getInstance().getMemoryCache()·get("url as key");