Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
32 changes: 19 additions & 13 deletions core/src/main/java/com/isbx/androidtools/media/ImageResizer.java
Original file line number Diff line number Diff line change
Expand Up @@ -43,15 +43,16 @@
*/
public class ImageResizer {

private static final int MAX_FILES = 10; // TODO handle files more intelligently
private static final int MAX_FILE_LIFESPAN = 86400000; // One day in milliseconds
private static final String FILE_NAME_FORMAT = "image%d.jpg";
private static final short JPEG_INITIAL_SHORT = (short) 0xffd8;

private Context context;
private ImageResizeConfig config;

private int savedFiles = 0;

private int prunedFiles = 0;

/**
* Creates a new ImageResizer that will use the given config to scale images.
*
Expand Down Expand Up @@ -218,9 +219,7 @@ public Uri scaleImage(Uri sourceUri, ImageResizeConfig.Dimension targetDimension

OutputStream os = null;
try {
if (savedFiles >= MAX_FILES) {
savedFiles = 0;
}
pruneFiles();
String fileName = String.format(Locale.US, FILE_NAME_FORMAT, savedFiles++);
os = context.openFileOutput(fileName, Context.MODE_PRIVATE);

Expand Down Expand Up @@ -331,16 +330,23 @@ public static Bitmap scaleBitmap(Bitmap source, ImageResizeConfig.Dimension targ
}

/**
* Deletes any temporary files that may have been created by previous resize operations. This
* will clear temporary files created by <strong>all</strong> ImageResizer instances, not just
* the current one.
* Deletes any files that are more than a day old. If all files are past this mark
* then the savedFiles and prunedFiles counts are reset.
*/
public void clearFiles() {
for (int i = 0; i < MAX_FILES; i++) {
String fileName = String.format(Locale.US, FILE_NAME_FORMAT, i);
public void pruneFiles() {
for (int i = 0; i < savedFiles; i++) {
if (prunedFiles == savedFiles) {
savedFiles = 0;
prunedFiles = 0;
break;
}
String fileName = String.format(Locale.US, FILE_NAME_FORMAT, i);
long lastModified = context.getFileStreamPath(fileName).lastModified();
if (System.currentTimeInMillis() - lastModified >= MAX_FILE_LIFESPAN) {
context.deleteFile(fileName);
}
savedFiles = 0;
prunedFiles++;
}
}
}

/**
Expand Down