Created
October 30, 2019 02:38
-
-
Save leoleozhu/c8c758ae54d83c64d92c7bad8835687b to your computer and use it in GitHub Desktop.
guess image content type from URL
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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