Skip to content

Instantly share code, notes, and snippets.

@aballano
Created February 9, 2018 11:11
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save aballano/62e7afa3a628853de33f3f4d2cb44bc3 to your computer and use it in GitHub Desktop.
Save aballano/62e7afa3a628853de33f3f4d2cb44bc3 to your computer and use it in GitHub Desktop.
isGif
public class UriUtil {
private final Context context;
private static final byte[] GIF89A_HEADER = {0x47, 0x49, 0x46, 0x38, 0x39, 0x61};
@Inject
public UriUtil(Context context) {
this.context = context;
}
public boolean isGif(Uri input) {
return hasMagicBytes(input, GIF89A_HEADER);
}
private boolean hasMagicBytes(Uri input, byte[] magicBytes) {
ContentResolver contentResolver = context.getContentResolver();
InputStream inputStream = null;
try {
inputStream = contentResolver.openInputStream(input);
if (inputStream == null) {
throw new IOException("cannot open input");
}
BufferedSource buffer = Okio.buffer(Okio.source(inputStream));
byte[] header = new byte[magicBytes.length];
buffer.read(header);
return Arrays.equals(header, magicBytes);
} catch (@SuppressWarnings("OverlyBroadCatchBlock") IOException e) {
Timber.w(e, "cannot determine file type");
return false;
} finally {
Utils.closeQuietly(inputStream);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment