Skip to content

Instantly share code, notes, and snippets.

@leoleozhu
Created October 30, 2019 02:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save leoleozhu/c8c758ae54d83c64d92c7bad8835687b to your computer and use it in GitHub Desktop.
Save leoleozhu/c8c758ae54d83c64d92c7bad8835687b to your computer and use it in GitHub Desktop.
guess image content type from URL
public class GuessContentTypeTest extends TestCase {
@Test
public void testGuessFileTypeFromUrl() throws Exception {
String[] urls = {
// your image urls here
};
for(String s : urls) {
int pushbackLimit = 100;
URL url = new URL(s);
URLConnection conn = url.openConnection();
InputStream urlStream = conn.getInputStream();
PushbackInputStream pushbackInputStream = new PushbackInputStream(urlStream, pushbackLimit);
byte[] firstBytes = new byte[pushbackLimit];
// download the first initial bytes into a byte array, which we will later pass to
// URLConnection.guessContentTypeFromStream
pushbackInputStream.read(firstBytes);
// push the bytes back onto the PushbackInputStream so that the stream can be read
// by ImageIO reader in its entirety
pushbackInputStream.unread(firstBytes);
String imageType = null;
// Pass the initial bytes to URLConnection.guessContentTypeFromStream in the form of a
// ByteArrayInputStream, which is mark supported.
ByteArrayInputStream bais = new ByteArrayInputStream(firstBytes);
String mimeType = URLConnection.guessContentTypeFromStream(bais);
if(mimeType == null) {
System.out.println("Cannot guess content type will use connection content-type header");
mimeType = conn.getContentType();
}
if (mimeType == null) {
System.out.println("Cannot guess and no content-type header");
}
else if (mimeType.startsWith("image/")) {
imageType = mimeType.substring("image/".length());
System.out.println(imageType);
}
else {
System.out.println("Not Image");
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment