I’m tidying up some code that uses javax.imageio.ImageIO. I have the file suffix the user is requesting, e.g. jpg, and we transform a saved image then render it back to the user in the correct format.
Now I want to map the suffix to the MIME type. This is relatively easy to do with a quick switch, but given that ImageIO has both
static Iterator<ImageWriter>getImageWritersBySuffix(String fileSuffix)static Iterator<ImageWriter>getImageWritersByMIMEType(String MIMEType)
it must know the mapping between suffix and MIME type, or the MIME type generated by a specific ImageWriter. Therefore there must be a way to get the content type from the writer that I’m about to use. But I don’t see any methods or properties on ImageWriter that return the content type, or even the suffices.
Essentially I’m trying to complete the following block of code:
Iterator<ImageWriter> imageWriters = ImageIO.getImageWritersBySuffix(type);
ImageWriter imageWriter = imageWriters.hasNext() ? imageWriters.next() : null;
if (imageWriter != null) {
contentType = imageWriter. ???
}
Thanks! The brute force approach I guess is to get all of the MIME types supported then iterate through those until I find one that returns the same ImageWriter as the get-by-suffix call (if indeed it’s easy to compare the results) but I’m hoping for something a little more elegant than that – I’d prefer a switch to that.
Try this: