I'm making that find duplicate images.
I'm using this code for to do this
private static boolean compare(Bitmap b1, Bitmap b2) {
if (b1.getWidth() == b2.getWidth() && b1.getHeight() == b2.getHeight()) {
int[] pixels1 = new int[b1.getWidth() * b1.getHeight()];
int[] pixels2 = new int[b2.getWidth() * b2.getHeight()];
b1.getPixels(pixels1, 0, b1.getWidth(), 0, 0, b1.getWidth(), b1.getHeight());
b2.getPixels(pixels2, 0, b2.getWidth(), 0, 0, b2.getWidth(), b2.getHeight());
if (Arrays.equals(pixels1, pixels2)) {
return true;
} else {
return false;
}
} else {
return false;
}
}
The code works fine, but it's very slow when i put a List of Images.
public static Bitmap getBitmapFromPath(String path){
File sd = Environment.getExternalStorageDirectory();
File image = new File(path);
BitmapFactory.Options bmOptions = new BitmapFactory.Options();
bmOptions.inPreferredConfig = Bitmap.Config.RGB_565;
bmOptions.inSampleSize = 2;
Bitmap bitmap = BitmapFactory.decodeFile(image.getAbsolutePath(),bmOptions);
return bitmap;
}
public static ArrayList<String> compareListOfImages(Activity activity){
ArrayList<String> pathList = FileUtils.getImagesPath(activity);
ArrayList<String> pathListResult = new ArrayList<>();
if(pathList!=null) {
for (int i = 0; i < pathList.size(); i++){
Log.d("I", i + " ITEM");
Bitmap bitmap1 = FileUtils.getBitmapFromPath(pathList.get(i));
for (int k =0; k <pathList.size(); k++){
Log.d("PATH", pathList.get(k));
Bitmap bitmap2 = FileUtils.getBitmapFromPath(pathList.get(k));
if(!pathList.get(i).equals(pathList.get(k))) {
if (FileUtils.compare(bitmap1, bitmap2)) {
pathListResult.add(pathList.get(k));
}
}
}
}
}
return pathListResult;
}
Someone know a othe way to get result more fast?
Related
I would like to save individual images (bitmap) of a GIF file and a video file. I want 5 pictures of each file. Depending on the length (seconds) of the files, the pictures should take pictures at regular intervals, so that there are 5 pictures. I hope someone can help me, thanks!
I found a good solution (for gifs) with Glide:
Glide.with(Activity.this)
.asGif()
.load(picturePath)
.into(new SimpleTarget<GifDrawable>() {
#Override
public void onResourceReady(#NonNull GifDrawable resource, #Nullable Transition<? super GifDrawable> transition) {
try {
Object GifState = resource.getConstantState();
Field frameLoader = GifState.getClass().getDeclaredField("frameLoader");
frameLoader.setAccessible(true);
Object gifFrameLoader = frameLoader.get(GifState);
Field gifDecoder = gifFrameLoader.getClass().getDeclaredField("gifDecoder");
gifDecoder.setAccessible(true);
StandardGifDecoder standardGifDecoder = (StandardGifDecoder) gifDecoder.get(gifFrameLoader);
for (int i = 0; i < standardGifDecoder.getFrameCount(); i++) {
standardGifDecoder.advance();
if (i == 4) {
bitmap1 = standardGifDecoder.getNextFrame();
} else if (i == standardGifDecoder.getFrameCount() / 3) {
bitmap2 = standardGifDecoder.getNextFrame();
} else if (i == standardGifDecoder.getFrameCount() / 2) {
bitmap3 = standardGifDecoder.getNextFrame();
} else if (i == standardGifDecoder.getFrameCount() - 4) {
bitmap4 = standardGifDecoder.getNextFrame();
}
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
});
you can use Android-Ndk-Gif library to handle your needs, and here's a full example of how to get each bitmap from GIF, you can change gifDecoder.frameNum() to 4 so you can get the first 5 frames from your GIF
GifDecoder gifDecoder = new GifDecoder();
boolean isSucceeded = gifDecoder.load(Path); // PATH OF YOUR IMAGE
ArrayList<BitmapGIFUtil> arrayListBitmaps = new ArrayList<>();
for (int i = 0; i < gifDecoder.frameNum(); ++i) {
Bitmap bitmap = gifDecoder.frame(i);
int GIFDelay = gifDecoder.delay(i);
arrayListBitmaps.add(new BitmapGIFUtil(bitmap, GIFDelay));
}
BitmapGIFUtil.java
public class BitmapGIFUtil {
private Bitmap bitmap;
private int Delay;
public BitmapGIFUtil() {
}
public BitmapGIFUtil(Bitmap bitmap, int delay) {
this.bitmap = bitmap;
Delay = delay;
}
public Bitmap getBitmap() {
return bitmap;
}
public void setBitmap(Bitmap bitmap) {
this.bitmap = bitmap;
}
public int getDelay() {
return Delay;
}
public void setDelay(int delay) {
Delay = delay;
}
}
After filling your arrayListBitmaps you can save each bitmap into your gallery
And here is a solution (for videos) with MediaMetadataRetriever:
MediaMetadataRetriever retriever = new MediaMetadataRetriever();
retriever.setDataSource(videoFile.getAbsolutePath());
MediaPlayer mp = MediaPlayer.create(getBaseContext(), vidUri);
mp.release();
String strLength = retriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_DURATION);
long time=Long.valueOf(strLength)*1000;
bitmap1 = retriever.getFrameAtTime(time/10*2,MediaMetadataRetriever.OPTION_CLOSEST_SYNC);
bitmap2 = retriever.getFrameAtTime(time/10*4,MediaMetadataRetriever.OPTION_CLOSEST_SYNC);
bitmap3 = retriever.getFrameAtTime(time/10*6,MediaMetadataRetriever.OPTION_CLOSEST_SYNC);
bitmap4 = retriever.getFrameAtTime(time/10*8,MediaMetadataRetriever.OPTION_CLOSEST_SYNC);
i want to fetch all photos from gallery and display it in grid view ..all photos i get but the problem is it will not working smoothly like as gallery too mach mobile hang please give me solution if any one have my code is below.
public class getImageFromGallery extends AsyncTask<String,Void,ArrayList<String>> {
#Override
protected ArrayList<String> doInBackground(String... strings) {
Uri u = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
String[] projection = {MediaStore.Images.ImageColumns.DATA};
Cursor c = null;
SortedSet<String> dirList = new TreeSet<String>();
final ArrayList<String> resultIAV = new ArrayList<String>();
String[] directories = null;
if (u != null)
{
String sortOrder ="_id asc limit 1";
c = managedQuery(u, projection, null, null, null);
}
if ((c != null) && (c.moveToFirst()))
{
do
{
String tempDir = c.getString(0);
tempDir = tempDir.substring(0, tempDir.lastIndexOf("/"));
try{
dirList.add(tempDir);
}
catch(Exception e)
{
}
}
while (c.moveToNext());
directories = new String[dirList.size()];
dirList.toArray(directories);
}
for(int i=0;i<dirList.size();i++)
{
File imageDir = new File(directories[i]);
File[] imageList = imageDir.listFiles();
if(imageList == null)
continue;
for (File imagePath : imageList) {
try {
if(imagePath.isDirectory())
{
imageList = imagePath.listFiles();
}
if ( imagePath.getName().contains(".jpg")|| imagePath.getName().contains(".JPG")
|| imagePath.getName().contains(".jpeg")|| imagePath.getName().contains(".JPEG")
|| imagePath.getName().contains(".png") || imagePath.getName().contains(".PNG")
|| imagePath.getName().contains(".gif") || imagePath.getName().contains(".GIF")
|| imagePath.getName().contains(".bmp") || imagePath.getName().contains(".BMP")
)
{
String path= imagePath.getAbsolutePath();
resultIAV.add(path);
}
}
// }
catch (Exception e) {
e.printStackTrace();
}
}
}
ShareMoment.this.runOnUiThread(new Runnable() {
#Override
public void run() {
shareMomentAdapter = new ShareMomentAdapter(ShareMoment.this,resultIAV);
sharemomentList.setAdapter(shareMomentAdapter);
}
});
return resultIAV;
}
}
public class ShareMomentAdapter extends RecyclerView.Adapter<ShareMomentAdapter.ShareMomentViewHolder> {
private Context context;
private ArrayList<String> shareMomentList;
ByteArrayOutputStream bytearrayoutputstream;
public ShareMomentAdapter(Context context, ArrayList<String> shareMomentList) {
this.shareMomentList = shareMomentList;
// shareMomentList = new ArrayList<>();
// for (int i = 0; i < 10; i++) {
// shareMomentList.add("" + i);
// }
this.context = context;
bytearrayoutputstream = new ByteArrayOutputStream();
}
#Override
public ShareMomentAdapter.ShareMomentViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.item_sharemoments, parent, false);
return new ShareMomentViewHolder(itemView);
}
#Override
public void onBindViewHolder(final ShareMomentAdapter.ShareMomentViewHolder holder, int position) {
Bitmap yourSelectedImage = BitmapFactory.decodeFile(shareMomentList.get(position));
final Bitmap resizedImage = Bitmap.createScaledBitmap(yourSelectedImage, 150, 150, true);
Glide.with(context).load(shareMomentList.get(position)).diskCacheStrategy(DiskCacheStrategy.RESULT).crossFade().into(holder.shareMomentImage);
}
#Override
public int getItemCount() {
return shareMomentList.size();
}
public class ShareMomentViewHolder extends RecyclerView.ViewHolder {
#Bind(R.id.shareMomentImage)
ImageView shareMomentImage;
// #Bind(R.id.nameTextview)
// TextView nameTextview;
// #Bind(R.id.descriptionTextView)
// TextView descriptionTextView;
private View view;
public ShareMomentViewHolder(View view) {
super(view);
this.view = view;
ButterKnife.bind(this, view);
}
}
public Bitmap getResizedBitmap(Bitmap bm, int newHeight, int newWidth) {
int width = bm.getWidth();
int height = bm.getHeight();
float scaleWidth = ((float) newWidth) / width;
float scaleHeight = ((float) newHeight) / height;
Matrix matrix = new Matrix();
matrix.postScale(scaleWidth, scaleHeight);
Bitmap resizedBitmap = Bitmap.createBitmap(bm, 0, 0, width, height,
matrix, false);
return resizedBitmap;
}
}
Try using LoadMoreView instead of loading all images at once. Load 10-20 images at a time, and then load more when user scrolls down. This will save a lot of memory.
I want to create the image of the barcode/QR code etc on my app. I have searched a lot and have found different libraries to do this task but since I am already using Zxing so i would like to work in it.
Following is the code that I have writen:
This is my Scanner Activity class:
public void handleResult(Result rawResult) {
// Do something with the result here
Log.v(TAG, rawResult.getText()); // Prints scan results
Toast.makeText(SimpleScannerActivity.this, rawResult.toString() + " WOW scanned", Toast.LENGTH_LONG).show();
Toast.makeText(SimpleScannerActivity.this, rawResult.getBarcodeFormat().toString(), Toast.LENGTH_LONG).show();
Log.v(TAG, rawResult.getBarcodeFormat().toString()); // Prints the scan format (qrcode, pdf417 etc.)
//Intent scanScreenResult= new Intent("com.aaa.fyp.ScanResultScreen");
setFormat(rawResult);
Intent nextScreen = new Intent("com.aaa.fyp.ScanResultScreen");
nextScreen.putExtra("barcode",rawResult.toString());
nextScreen.putExtra("format", rawResult.getBarcodeFormat().toString());
finish();
startActivity(nextScreen);
}
public void setFormat(Result result){
r=result.getBarcodeFormat();
System.out.println("============================== setformat main"+ r);
}
public BarcodeFormat getFormat(){
System.out.println("============================== getformat main"+ r);
return r;
}
Using the results from the above activity in ScanResultScreen activity.
public class ScanResultScreen extends SimpleScannerActivity {
ImageView scanned;
TextView bc;
TextView f;
String Barcode;
String format;
BarcodeFormat form;
#Override
public void onCreate(Bundle state) {
super.onCreate(state);
setContentView(R.layout.scan_screen_with_button);
ViewGroup layout = (ViewGroup) findViewById(R.id.scanScreenWithButton);
setContentView(layout);
Intent prevScreen = getIntent(); // gets the previously created intent
Barcode=prevScreen.getStringExtra("barcode");
bc= (TextView)findViewById(R.id.barcode_label);
bc.setText(Barcode);
format=prevScreen.getStringExtra("format");
f=(TextView) findViewById(R.id.format_label);
f.setText(prevScreen.getStringExtra("format").toString());
SimpleScannerActivity obj=new SimpleScannerActivity();
form=obj.getFormat();
d=(TextView)findViewById(R.id.date_label);
String formattedDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(Calendar.getInstance().getTime());
d.setText(formattedDate);
Bitmap bitmap = null;
ImageView iv = new ImageView(this);
try {
bitmap = encodeAsBitmap(Barcode, form, 600, 300);
iv.setImageBitmap(bitmap);
} catch (WriterException e) {
e.printStackTrace();
}
layout.addView(iv);
}
private static final int WHITE = 0xFFFFFFFF;
private static final int BLACK = 0xFF000000;
Bitmap encodeAsBitmap(String contents, BarcodeFormat format, int img_width, int img_height) throws WriterException {
String contentsToEncode = contents;
if (contentsToEncode == null) {
return null;
}
Map<EncodeHintType, Object> hints = null;
String encoding = guessAppropriateEncoding(contentsToEncode);
if (encoding != null) {
hints = new EnumMap<EncodeHintType, Object>(EncodeHintType.class);
hints.put(EncodeHintType.CHARACTER_SET, encoding);
}
MultiFormatWriter writer = new MultiFormatWriter();
BitMatrix result;
try {
result = writer.encode(contentsToEncode, format, img_width, img_height, hints);
} catch (IllegalArgumentException iae) {
// Unsupported format
return null;
}
int width = result.getWidth();
int height = result.getHeight();
int[] pixels = new int[width * height];
for (int y = 0; y < height; y++) {
int offset = y * width;
for (int x = 0; x < width; x++) {
pixels[offset + x] = result.get(x, y) ? BLACK : WHITE;
}
}
Bitmap bitmap = Bitmap.createBitmap(width, height,
Bitmap.Config.ARGB_8888);
bitmap.setPixels(pixels, 0, width, 0, 0, width, height);
return bitmap;
}
private static String guessAppropriateEncoding(CharSequence contents) {
// Very crude at the moment
for (int i = 0; i < contents.length(); i++) {
if (contents.charAt(i) > 0xFF) {
return "UTF-8";
}
}
return null;
}
Now I am getting a Null value in the variable "form". Even though I am able to get the barcodeFormat in my second activity by passing it through intent but it's in the type String. Whereas the built-in methods that I am using here requires it in BarcodeFormat that is available in Zxing.
Help!!
BarcodeFormat is an enum type. If you want to pass a String value, you have to convert it to BarcodeFormat.
For example, passing a barcode format "AZTEC":
BarcodeFormat format = Enum.valueOf(BarcodeFormat.class, "AZTEC");
I have seen many answers on this issue which has not worked so far for me, the best option I got was using a Picasso to solve this, I have imported the .jar but am getting an error on the code I was told to use, I get an error on this(context) in the following line of code, say (context) cannot be resolved to a variable
Picasso.with(context).load(myBitmap).into(imageView);
This is the lines of code that generates the error, which I intend solving using Picasso
File imgFile = new File(data.get(position).get("path"));
Bitmap myBitmap = BitmapFactory.decodeFile(imgFile.getAbsolutePath());
imageView.setImageBitmap(myBitmap);
This is my full code below
public class WidgetActivity extends Activity {
GridView grid;
Matrix matrix = new Matrix();
Bitmap rotateimage;
ArrayList<HashMap<String, String>> maplist = new ArrayList<HashMap<String,String>>();
LocalStorageHandler notedb;
ImageView iv_notes;
EditText content;
LinearLayout grid_layout;
AppWidgetManager appWidgetManager;
int n;
Intent i;
int s;
String[] tcolor;
public String path = "", name = "", color = "";
public void onCreate(Bundle os) {
super.onCreate(os);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.dialog_shownotes);
notedb = new LocalStorageHandler(WidgetActivity.this);
grid = (GridView) findViewById(R.id.grid);
iv_notes = (ImageView) findViewById(R.id.iv_note);
content = (EditText) findViewById(R.id.content);
grid_layout = (LinearLayout) findViewById(R.id.grid_layout);
i = getIntent();
n = i.getIntExtra("currentWidgetId", 1);
new getlist().execute();
}
class getlist extends AsyncTask<String, String, String> {
ArrayList<HashMap<String, String>> maplist = new ArrayList<HashMap<String, String>>();
#Override
public void onPreExecute() {
super.onPreExecute();
}
#Override
protected String doInBackground(String... arg) {
ArrayList<String> filepaths = new ArrayList<String>();
ArrayList<String> filenames = new ArrayList<String>();
Cursor dbCursor = notedb.get();
if (dbCursor.getCount() > 0) {
int noOfScorer = 0;
dbCursor.moveToFirst();
while ((!dbCursor.isAfterLast())
&& noOfScorer < dbCursor.getCount()) {
noOfScorer++;
try {
HashMap<String, String> items = new HashMap<String, String>();
filepaths.add(Environment.getExternalStorageDirectory()
+ "/360notes/" + dbCursor.getString(2));
filenames.add(dbCursor.getString(3));
items.put("path",
Environment.getExternalStorageDirectory()
+ "/360notes/" + dbCursor.getString(2));
items.put("name", dbCursor.getString(3));
items.put("time", dbCursor.getString(1));
items.put("id", dbCursor.getString(0));
items.put("color", dbCursor.getString(4));
maplist.add(items);
} catch (Exception e) {
e.printStackTrace();
}
dbCursor.moveToNext();
}
}
return null;
}
#Override
protected void onPostExecute(String unused) {
if (maplist.size() > 0) {
grid.setAdapter(new GridViewImageAdapter(WidgetActivity.this,
maplist));
}
}
}
public class GridViewImageAdapter extends BaseAdapter {
private Activity _activity;
ArrayList<String> _filenames = new ArrayList<String>();
private ArrayList<HashMap<String, String>> data = new ArrayList<HashMap<String, String>>();
public GridViewImageAdapter(Activity activity,
ArrayList<HashMap<String, String>> items) {
this._activity = activity;
data = items;
}
#Override
public int getCount() {
return data.size();
}
#Override
public Object getItem(int position) {
return position;
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(final int position, View convertView,
ViewGroup parent) {
LayoutInflater inflate = (LayoutInflater) _activity
.getSystemService(_activity.LAYOUT_INFLATER_SERVICE);
convertView = inflate.inflate(R.layout.show_image, null);
ImageView imageView = (ImageView) convertView
.findViewById(R.id.imgScreen);
TextView title = (TextView) convertView.findViewById(R.id.title);
try {
String[] tcolor = data.get(position).get("name").split(" / ");
title.setText(tcolor[0].trim());
title.setTextColor(Color.parseColor(tcolor[1].trim()));
if (tcolor[2].trim().equals("0")) {
String text = title.getText().toString();
SpannableString span = new SpannableString(text);
span.setSpan(new UnderlineSpan(), 0, span.length(), 0);
// title.setText(span);
} else if (tcolor[2].trim().equals("3")) {
// title.setTypeface(null, Typeface.BOLD);
String text = title.getText().toString();
SpannableString span = new SpannableString(text);
span.setSpan(new UnderlineSpan(), 0, span.length(), 0);
// title.setText(span);
} else if (tcolor[2].trim().equals("4")) {
// title.setTypeface(null, Typeface.ITALIC);
String text = title.getText().toString();
SpannableString span = new SpannableString(text);
span.setSpan(new UnderlineSpan(), 0, span.length(), 0);
// title.setText(span);
} else if (tcolor[2].trim().equals("1")) {
// title.setTypeface(null, Typeface.BOLD);
String text = title.getText().toString();
SpannableString span = new SpannableString(text);
span.removeSpan(text);
} else if (tcolor[2].trim().equals("2")) {
// title.setTypeface(null, Typeface.ITALIC);
String text = title.getText().toString();
SpannableString span = new SpannableString(text);
span.removeSpan(text);
} else {
String text = title.getText().toString();
SpannableString span = new SpannableString(text);
span.removeSpan(text);
}
} catch (IndexOutOfBoundsException e) {
// TODO: handle exception
}
// TODO: handle exception
BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = 4;
File imgFile = new File(data.get(position).get("path"));
Bitmap myBitmap = BitmapFactory.decodeFile(imgFile.getAbsolutePath());
imageView.setImageBitmap(myBitmap);
/*if (myBitmap != null && !myBitmap.isRecycled()) {
myBitmap.recycle();
myBitmap = null;
}*/
//myBitmap.recycle();
//myBitmap = null;
Picasso.with(context).load(myBitmap).into(imageView);
grid.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
grid.setVisibility(View.GONE);
// grid_layout.setVisibility(View.VISIBLE);
s = position;
path = data.get(position).get("path");
try {
tcolor = data.get(position).get("name").split(" / ");
name = tcolor[0].trim();
color = tcolor[1].trim();
} catch (IndexOutOfBoundsException e) {
name = "";
color = "#000000";
}
appWidgetManager = AppWidgetManager
.getInstance(WidgetActivity.this);
UnreadWidgetProvider.updateWidget(WidgetActivity.this,
appWidgetManager, n, path,
data.get(position).get("name"), color, s);
finish();
}
});
return convertView;
}
}
public void images(String path, String name, String color) {
try {
Bitmap bm;
try {
bm = decodeSampledBitmapFromResource(path);
ExifInterface exifReader = new ExifInterface(path);
int orientation = exifReader.getAttributeInt(
ExifInterface.TAG_ORIENTATION, -1);
if (orientation == ExifInterface.ORIENTATION_NORMAL) {
matrix.postRotate(360);
} else if (orientation == ExifInterface.ORIENTATION_ROTATE_90) {
// matrix.postRotate(90);
} else if (orientation == ExifInterface.ORIENTATION_ROTATE_180) {
// matrix.postRotate(180);
} else if (orientation == ExifInterface.ORIENTATION_ROTATE_270) {
// matrix.postRotate(270);
} else if (orientation == ExifInterface.ORIENTATION_UNDEFINED) {
// matrix.postRotate(90);
} else {
}
rotateimage = Bitmap.createBitmap(bm, 0, 0, bm.getWidth(),
bm.getHeight(), matrix, true);
iv_notes.setImageBitmap(rotateimage);
content.setText(name);
content.setFocusable(false);
try {
String[] tcolor = name.split(" / ");
content.setText(tcolor[0].trim());
content.setTextColor(Color.parseColor(tcolor[1].trim()));
if (tcolor[2].trim().equals("0")) {
String text = content.getText().toString();
SpannableString span = new SpannableString(text);
span.setSpan(new UnderlineSpan(), 0, span.length(), 0);
// content.setText(span);
} else if (tcolor[2].trim().equals("3")) {
// content.setTypeface(null, Typeface.BOLD);
String text = content.getText().toString();
SpannableString span = new SpannableString(text);
span.setSpan(new UnderlineSpan(), 0, span.length(), 0);
// content.setText(span);
} else if (tcolor[2].trim().equals("4")) {
// content.setTypeface(null, Typeface.ITALIC);
String text = content.getText().toString();
SpannableString span = new SpannableString(text);
span.setSpan(new UnderlineSpan(), 0, span.length(), 0);
// content.setText(span);
} else if (tcolor[2].trim().equals("1")) {
// content.setTypeface(null, Typeface.BOLD);
String text = content.getText().toString();
SpannableString span = new SpannableString(text);
span.removeSpan(text);
} else if (tcolor[2].trim().equals("2")) {
// content.setTypeface(null, Typeface.ITALIC);
String text = content.getText().toString();
SpannableString span = new SpannableString(text);
span.removeSpan(text);
} else {
String text = content.getText().toString();
SpannableString span = new SpannableString(text);
span.removeSpan(text);
}
} catch (IndexOutOfBoundsException e) {
// TODO: handle exception
}
grid_layout.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
int i = grid.getCount();
Intent intentAlarm = new Intent(WidgetActivity.this,
WriteNotesActivity.class);
intentAlarm.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
| Intent.FLAG_ACTIVITY_SINGLE_TOP);
intentAlarm.putExtra("max", s);
startActivity(intentAlarm);
finish();
}
});
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
} catch (Exception e) {
// finish();
}
}
public static Bitmap decodeSampledBitmapFromResource(String resId) {
// First decode with inJustDecodeBounds=true to check dimensions
final BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeFile(resId, options);
// Calculate inSampleSize
options.inSampleSize = calculateInSampleSize(options, 400, 300);
// Decode bitmap with inSampleSize set
options.inJustDecodeBounds = false;
return BitmapFactory.decodeFile(resId, options);
}
public static int calculateInSampleSize(BitmapFactory.Options options,
int reqWidth, int reqHeight) {
// Raw height and width of image
final int height = options.outHeight;
final int width = options.outWidth;
int inSampleSize = 1;
if (height > reqHeight || width > reqWidth) {
final int halfHeight = height / 2;
final int halfWidth = width / 2;
// Calculate the largest inSampleSize value that is a power of 2 and
// keeps both
// height and width larger than the requested height and width.
while ((halfHeight / inSampleSize) > reqHeight
|| (halfWidth / inSampleSize) > reqWidth) {
inSampleSize *= 2;
}
}
return inSampleSize;
}
}
This might help someone out there after several hours without an answer to this. I found a way of solving this without using Picasso in handling the outOfMemoryError. I added this line of code in my Manifest file.
android:largeHeap="true"
I added this to the entire application here as below:-
<application
android:icon="#drawable/ic_launcher"
android:largeHeap="true"
android:label="#string/app_name" >
android:largeHeap is the instrument for increasing your allocated memory to app.
EDIT:
well, you are using too much memory. remove those 3 lines of code :
File imgFile = new File(data.get(position).get("path"));
Bitmap myBitmap = BitmapFactory.decodeFile(imgFile.getAbsolutePath());
imageView.setImageBitmap(myBitmap);
simply, you are assigning too much space to these instances and your phone runs out of memory. Just use my response and consider logging the file path so you can possibly use that without creating another file.
i think you used wrong implementation. Probably the context is not adressing correctly and therefore, i would personally use "this" instead. And for loading resources, their guide provides us with three implementations, see below:
pass drawable
Picasso.with(context).load(R.drawable.landing_screen).into(imageView1);
pass uri
Picasso.with(context).load("file:///android_asset/DvpvklR.png").into(imageView2);
pass file
Picasso.with(context).load(new File(...)).into(imageView3);
so therefore i would decode the image using this code:
Picasso.with(this).load(new File(data.get(position).get("path"))).into(imageView);
Mat last;
//Mat last2;
ArrayList<Scene> scenes = new ArrayList<Scene>();
//ArrayList<Scene> scenes23 = new ArrayList<Scene>();
ArrayList<Bitmap> myImageList2 = new ArrayList<Bitmap>();
int[] myImageList = new int[]{R.drawable.baldglassy,
R.drawable.baldglassy2,
R.drawable.bandedarcherfish,
R.drawable.bandedarcherfish2,
R.drawable.bluegill,
R.drawable.bluegill2,
R.drawable.bluespotmullet};
/*Bitmap[] images2 = { BitmapFactory.decodeResource(getResources(),R.drawable.baldglassy),
BitmapFactory.decodeResource(getResources(),R.drawable.baldglassy2),
BitmapFactory.decodeResource(getResources(),R.drawable.bandedarcherfish),
BitmapFactory.decodeResource(getResources(),R.drawable.bluegill),
BitmapFactory.decodeResource(getResources(),R.drawable.bluegill2),
BitmapFactory.decodeResource(getResources(),R.drawable.bluespotmullet),
};*/
Scene refScene;
ProgressDialog progress;
//Mat imgMAT;
public void takePic1(View w) {
//Bitmap bmp32 = images[](Bitmap.Config.ARGB_8888, true);
/*for(int i=0;i<=5;i++){
Bitmap bmp32 = images[i].copy(Bitmap.Config.ARGB_8888, true);
Utils.bitmapToMat(bmp32, imgMAT);
}
Scene scene2 = new Scene(imgMAT);
scenes.add(scene2);*/
Scene scene = new Scene(last);
scenes.add(scene);
addBtn.setText("Add (" + scenes.size() + ")");
}
public void takePic2(View w) {
Mat im = last.clone();
// Imgproc.cvtColor(im, im, Imgproc.COLOR_BGR2RGB);
Bitmap bmp = Bitmap.createBitmap(im.cols(), im.rows(),
Bitmap.Config.ARGB_8888);
Utils.matToBitmap(im, bmp);
matchDrawArea.setImageBitmap(bmp);
refScene = new Scene(last);
}
when i use a bitmap array, the app crashes
it says that change the type of my int array to Scene. But it is impossible. Thanks in advance to those who will help.
here is the scene class
public class Scene {
final Mat image;
final Mat descriptors = new Mat();
final MatOfKeyPoint keypoints = new MatOfKeyPoint();
boolean firstTime = true;
public Scene(Mat image) {
this.image = image.clone();
// DetectUtility.analyze(image, keypoints, descriptors);
}
public void preCompute() {
if (firstTime) {
DetectUtility.analyze(image, keypoints, descriptors);
firstTime = false;
}
}
public SceneDetectData compare(Scene frame, boolean isHomogrpahy, boolean imageOnly) {
// Info to store analysis stats
SceneDetectData s = new SceneDetectData();
// Detect key points and compute descriptors for inputFrame
MatOfKeyPoint f_keypoints = frame.keypoints;
Mat f_descriptors = frame.descriptors;
this.preCompute();
frame.preCompute();
// Compute matches
MatOfDMatch matches = DetectUtility.match(descriptors, f_descriptors);
// Filter matches by distance
MatOfDMatch filtered = DetectUtility.filterMatchesByDistance(matches);
// If count of matches is OK, apply homography check
s.original_key1 = (int) descriptors.size().height;
s.original_key2 = (int) f_descriptors.size().height;
s.original_matches = (int) matches.size().height;
s.dist_matches = (int) filtered.size().height;
if (isHomogrpahy) {
MatOfDMatch homo = DetectUtility.filterMatchesByHomography(
keypoints, f_keypoints, filtered);
Bitmap bmp = DetectUtility.drawMatches(image, keypoints,
frame.image, f_keypoints, homo, imageOnly);
s.bmp = bmp;
s.homo_matches = (int) homo.size().height;
return s;
} else {
Bitmap bmp = DetectUtility.drawMatches(image, keypoints,
frame.image, f_keypoints, filtered, imageOnly);
s.bmp = bmp;
s.homo_matches = -1;
return s;
}
}
}