Attempt to obtain the image format used to write the image from the contentType or the image's file extension.
197218
private String guessImageFormat(String contentType, String imagePath) throws IOException {

        String format = "png";

        if (contentType == null) {
            contentType = URLConnection.guessContentTypeFromName(imagePath);
        }

        if (contentType != null) {
            format = contentType.replaceFirst("^image/([^;]+)[;]?.*$", "$1");
        }
        else {
            int queryStringIndex = imagePath.indexOf('?');

            if (queryStringIndex != -1) {
                imagePath = imagePath.substring(0, queryStringIndex);
            }

            String[] pathTokens = imagePath.split("\\.");

            if (pathTokens.length > 1) {
                format = pathTokens[pathTokens.length - 1];
            }
        }

        return format;
    }
70517
public void flush() throws IOException {
        String outputType = getOutputContentType();

        // Force transcoding, if no other filtering is done
        if (outputType != null && !outputType.equals(originalContentType)) {
            getImage();
        }

        if (image != null) {
            Iterator writers = ImageIO.getImageWritersByMIMEType(outputType);
            if (writers.hasNext()) {
                super.setContentType(outputType);
                OutputStream out = super.getOutputStream();
                try {
                    ImageWriter writer = (ImageWriter) writers.next();
                    try {
                        ImageWriteParam param = writer.getDefaultWriteParam();
    ///////////////////
    // POST-PROCESS
                        // For known formats that don't support transparency, convert to opaque
                        if (isNonAlphaFormat(outputType) && image.getColorModel().getTransparency() != Transparency.OPAQUE) {
                            image = ImageUtil.toBuffered(image, BufferedImage.TYPE_INT_RGB);
                        }

                        Float requestQuality = (Float) originalRequest.getAttribute(ImageServletResponse.ATTRIB_OUTPUT_QUALITY);

                        // The default JPEG quality is not good enough, so always adjust compression/quality
                        if ((requestQuality != null || "jpeg".equalsIgnoreCase(getFormatNameSafe(writer))) && param.canWriteCompressed()) {
                            // TODO: See http://blog.apokalyptik.com/2009/09/16/quality-time-with-your-jpegs/ for better adjusting the (default) JPEG quality
                            // OR: Use the metadata of the original image

                            param.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);

                            // WORKAROUND: Known bug in GIFImageWriter in certain JDK versions, compression type is not set by default
                            if (param.getCompressionTypes() != null && param.getCompressionType() == null) {
                                param.setCompressionType(param.getCompressionTypes()[0]); // Just choose any, to keep param happy
                            }

                            param.setCompressionQuality(requestQuality != null ? requestQuality : 0.8f);
                        }

                        if ("gif".equalsIgnoreCase(getFormatNameSafe(writer)) && !(image.getColorModel() instanceof IndexColorModel) 
                                /*&& image.getColorModel().getTransparency() != Transparency.OPAQUE*/) {
                            // WORKAROUND: Bug in GIFImageWriter may throw NPE if transparent pixels
                            // See: http://bugs.sun.com/view_bug.do?bug_id=6287936
                            image = ImageUtil.createIndexed(
                                    ImageUtil.toBuffered(image), 256, null,
                                    (image.getColorModel().getTransparency() == Transparency.OPAQUE ? ImageUtil.TRANSPARENCY_OPAQUE : ImageUtil.TRANSPARENCY_BITMASK) | ImageUtil.DITHER_DIFFUSION_ALTSCANS
                            );
                        }
    //////////////////
                        ImageOutputStream stream = ImageIO.createImageOutputStream(out);

                        writer.setOutput(stream);
                        try {
                            writer.write(null, new IIOImage(image, null, null), param);
                        }
                        finally {
                            stream.close();
                        }
                    }
                    finally {
                        writer.dispose();
                    }
                }
                finally {
                    out.flush();
                }
            }
            else {
                context.log("ERROR: No writer for content-type: " + outputType);
                throw new IIOException("Unable to transcode image: No suitable image writer found (content-type: " + outputType + ").");
            }
        }
        else {
            super.setContentType(originalContentType);

            ServletOutputStream out = super.getOutputStream();

            try {
                if (bufferedOut != null) {
                    bufferedOut.writeTo(out);
                }
            }
            finally {
                out.flush();
            }
        }
    }
194374
def _get_image_data(image, colors):
    
    lzw_code_size, coded_bits = _lzw_encode(image, colors)
    coded_bytes = ''.join(
        '{{:0{}b}}'.format(nbits).format(val) for val, nbits in coded_bits)
    coded_bytes = '0' * ((8 - len(coded_bytes)) % 8) + coded_bytes
    coded_data = list(
        reversed([
            int(coded_bytes[8*i:8*(i+1)], 2)
            for i in range(len(coded_bytes) // 8)
        ])
    )
    output = [struct.pack('<B', lzw_code_size)]
    # Must output the data in blocks of length 255
    block_length = min(255, len(coded_data))
    while block_length > 0:
        block = struct.pack(
            '<{}B'.format(block_length + 1),
            block_length,
            *coded_data[:block_length]
        )
        output.append(block)
        coded_data = coded_data[block_length:]
        block_length = min(255, len(coded_data))
    return b''.join(output)
816383
public static String fileExtensionForMIMEType(String mimeType) {
        loadMappings();

        String ext = mimeTypeToExtensionMap.get(mimeType);

        if (ext == null) ext = "dat";

        return ext;
    }
838847
function getImageDataType (image) {
  if (image.color) {
    return 'rgb';
  }

  const pixelData = image.getPixelData();

  if (pixelData instanceof Int16Array) {
    return 'int16';
  }

  if (pixelData instanceof Uint16Array) {
    return 'uint16';
  }

  if (pixelData instanceof Int8Array) {
    return 'int8';
  }

  return 'uint8';
}
569136
function getFileTypeReg(type) {
    var map = [],
        ext = ""; // fis.config.get('project.fileType.' + type);
    if (type === 'text') {
        map = TEXT_FILE_EXTS;
    } else if (type === 'image') {
        map = IMAGE_FILE_EXTS;
    } else {
        xgulp.log.error('invalid file type [%s]', type);
    }
    if (ext && ext.length) {
        if (typeof ext === 'string') {
            ext = ext.split(/\s*,\s*/);
        }
        map = map.concat(ext);
    }
    map = map.join('|');
    return new RegExp('\\.(?:' + map + ')$', 'i');
}
173530
def content_type
      type = (self.path.match(/\.(\w+)$/)[1] rescue "octet-stream").downcase
      case type
      when %r"jp(e|g|eg)"            then "image/jpeg"
      when %r"tiff?"                 then "image/tiff"
      when %r"png", "gif", "bmp"     then "image/#{type}"
      when "txt"                     then "text/plain"
      when %r"html?"                 then "text/html"
      when "js"                      then "application/js"
      when "csv", "xml", "css"       then "text/#{type}"
      else
        # On BSDs, `file` doesn't give a result code of 1 if the file doesn't exist.
        content_type = (Paperclip.run("file", "-b --mime-type :file", :file => self.path).split(':').last.strip rescue "application/x-#{type}")
        content_type = "application/x-#{type}" if content_type.match(/\(.*?\)/)
        content_type
      end
    end
66839
def _getImageSize(filename):
    """"""
    result = None
    file = open(filename, 'rb')
    if file.read(8) == b'\x89PNG\r\n\x1a\n': # PNG
        while 1:
            length, = _struct.unpack('>i', file.read(4))
            chunkID = file.read(4)
            if chunkID == '': # EOF
                break
            if chunkID == b'IHDR':
                # return width, height
                result = _struct.unpack('>ii', file.read(8))
                break
            file.seek(4 + length, 1)
        file.close()
        return result
    file.seek(0)
    if file.read(8) == b'BM': # Bitmap
        file.seek(18, 0) # skip to size data
        result = _struct.unpack('<ii', file.read(8))
    file.close()
    return result
336286
public String getContentType() {
        if (contentType == null)
            contentType = getHeaderField("content-type");
        if (contentType == null) {
            String ct = null;
            try {
                ct = guessContentTypeFromStream(getInputStream());
            } catch(java.io.IOException e) {
            }
            String ce = properties.findValue("content-encoding");
            if (ct == null) {
                ct = properties.findValue("content-type");

                if (ct == null)
                    if (url.getFile().endsWith("/"))
                        ct = "text/html";
                    else
                        ct = guessContentTypeFromName(url.getFile());
            }

            /*
             * If the Mime header had a Content-encoding field and its value
             * was not one of the values that essentially indicate no
             * encoding, we force the content type to be unknown. This will
             * cause a save dialog to be presented to the user.  It is not
             * ideal but is better than what we were previously doing, namely
             * bringing up an image tool for compressed tar files.
             */

            if (ct == null || ce != null &&
                    !(ce.equalsIgnoreCase("7bit")
                      || ce.equalsIgnoreCase("8bit")
                      || ce.equalsIgnoreCase("binary")))
                ct = "content/unknown";
            setContentType(ct);
        }
        return contentType;
    }
74919
public static String getExternalGraphicFormat( String name ) {
        String format = "";
        if (name.toLowerCase().endsWith(".png")) {
            format = "image/png";
        } else if (name.toLowerCase().endsWith(".jpg")) {
            format = "image/jpg";
        } else if (name.toLowerCase().endsWith(".gif")) {
            format = "image/gif";
        } else if (name.toLowerCase().endsWith(".svg")) {
            format = "image/svg+xml";
        } else {
            return null;
        }

        return format;
    }
15971
public ImageHeuristics getImageSizes(String imgFileName) throws
      IOException
  {
    int pos = imgFileName.lastIndexOf(".");
    if (pos == -1)
    {
      throw new IOException("No extension for file: " + imgFileName);
    }

    String suffix = imgFileName.substring(pos + 1);
    File tempFile = null;
    if ("svg".compareToIgnoreCase(suffix) == 0)
    {
      tempFile = getImageFile(ocf, imgFileName);
      if (tempFile != null)
      {
          long tempFileLength = tempFile.length();
          if (ocf.getClass() == OCFZipPackage.class)
          {
              tempFile.delete();
          }
        return new ImageHeuristics(0, 0, tempFileLength);
      }
      return null;
    }
    
    // Determine format by file extension and by inspecting the file
    tempFile = getImageFile(ocf, imgFileName);
    String formatFromInputStream = null;
    String formatFromSuffix = null;
    ImageInputStream imageInputStream = ImageIO.createImageInputStream(tempFile);
    Iterator<ImageReader> imageReaderIteratorFromInputStream = ImageIO.getImageReaders(imageInputStream);
    while (imageReaderIteratorFromInputStream.hasNext()) {
      ImageReader imageReaderFromInputStream = imageReaderIteratorFromInputStream.next();
      formatFromInputStream = imageReaderFromInputStream.getFormatName();
        
      Iterator<ImageReader> imageReaderIteratorFromSuffix = ImageIO.getImageReadersBySuffix(suffix);
        while (imageReaderIteratorFromSuffix.hasNext()) {
          ImageReader reader = imageReaderIteratorFromSuffix.next();
          formatFromSuffix = reader.getFormatName();
          
          if (formatFromSuffix != null && formatFromSuffix.equals(formatFromInputStream)) break;
        }
        if (formatFromSuffix != null && formatFromSuffix.equals(formatFromInputStream)) break;
    }
    imageInputStream.close();



      if (formatFromSuffix != null && formatFromSuffix.equals(formatFromInputStream)) {
      // file format and file extension matches; read image file
      
      try {
        BufferedImage image = ImageIO.read(tempFile);
        if (image == null) {
          report.message(MessageId.PKG_021, EPUBLocation.create(imgFileName));
          return null;
          
        } else {
          int width          = image.getWidth();
          int height         = image.getHeight();
          return new ImageHeuristics(width, height, tempFile.length());
        }
      }
      catch (IOException e)
      {
        report.message(MessageId.PKG_021, EPUBLocation.create(imgFileName));
        return null;
      }
      catch (RuntimeException argex)
      {
        report.message(MessageId.PKG_021, EPUBLocation.create(imgFileName));
        return null;
      }
      finally
      {
          if (ocf.getClass() == OCFZipPackage.class)
          {
              tempFile.delete();
          }
      }
  
    } else
      {
          if (ocf.getClass() == OCFZipPackage.class)
          {
              tempFile.delete();
          }
          if (formatFromSuffix != null) {
              // file format and file extension differs

              report.message(MessageId.PKG_022, EPUBLocation.create(imgFileName), formatFromInputStream, suffix);
              return null;

          } else {
              // file format could not be determined

              throw new IOException("Not a known image file: " + imgFileName);
          }
      }
  }
843082
function image(filename) {
  if (!filename) return;
  var ext = filename.split('.')[filename.split('.').length - 1];
  return ~extensions.join().indexOf(ext);
}
933001
def guessImageFormatFromHttpResponse(response):
    
    extensions = []

    # try to guess extension from response content-type header
    try:
      content_type = response.headers["Content-Type"]
    except KeyError:
      pass
    else:
      ext = mimetypes.guess_extension(content_type, strict=False)
      if ext is not None:
        extensions.append(ext)

    # try to extract extension from URL
    urls = list(response.history) + [response.url]
    for url in map(str, urls):
      ext = os.path.splitext(urllib.parse.urlsplit(url).path)[-1]
      if (ext is not None) and (ext not in extensions):
        extensions.append(ext)

    # now guess from the extensions
    for ext in extensions:
      try:
        return SUPPORTED_IMG_FORMATS[ext[1:]]
      except KeyError:
        pass
26153
def image_format(value):
    

    if value.image.format.upper() not in constants.ALLOWED_IMAGE_FORMATS:
        raise ValidationError(MESSAGE_INVALID_IMAGE_FORMAT)
129873
protected <T extends ImageBase> ImageType<T> getImageType( int which ) {
		synchronized ( inputStreams ) {
			return inputStreams.get(which).imageType;
		}
	}
1018453
function (format) {
        if (!this.image || !this.size) return null;

        format = format || "image/png";
        var canvas = document.createElement("canvas");
        var context = canvas.getContext("2d");
        context.canvas.width = this.size.w;
        context.canvas.height = this.size.h;

        var imgData = context.createImageData(this.size.w, this.size.h);
        for (var i = 0; i < this.image.length; i++) {
            imgData.data[i] = this.image[i];
        }
        context.putImageData(imgData, 0, 0);
        
        return canvas.toDataURL(format);
    }
776303
def format(self):
        
        if self._format:
            return self._format
        elif self.pil_image:
            return self.pil_image.format