Get Image dimensions
@param {object} metaData
@returns {object} metaData
@description for image properties in meta data (coverImage, authorImage and blog.logo), `getCachedImageSizeFromUrl` is
called to receive image width and height
195936
function getImageDimensions(metaData) {
    var fetch = {
        coverImage: imageLib.imageSizeCache(metaData.coverImage.url),
        authorImage: imageLib.imageSizeCache(metaData.authorImage.url),
        ogImage: imageLib.imageSizeCache(metaData.ogImage.url),
        logo: imageLib.imageSizeCache(metaData.blog.logo.url)
    };

    return Promise
        .props(fetch)
        .then(function (imageObj) {
            _.forEach(imageObj, function (key, value) {
                if (_.has(key, 'width') && _.has(key, 'height')) {
                    // We have some restrictions for publisher.logo:
                    // The image needs to be <=600px wide and <=60px high (ideally exactly 600px x 60px).
                    // Unless we have proper image-handling (see https://github.com/TryGhost/Ghost/issues/4453),
                    // we will fake it in some cases or not produce an imageObject at all.
                    if (value === 'logo') {
                        if (key.height <= 60 && key.width <= 600) {
                            _.assign(metaData.blog[value], {
                                dimensions: {
                                    width: key.width,
                                    height: key.height
                                }
                            });
                        } else if (key.width === key.height) {
                            // CASE: the logo is too large, but it is a square. We fake it...
                            _.assign(metaData.blog[value], {
                                dimensions: {
                                    width: 60,
                                    height: 60
                                }
                            });
                        }
                    } else {
                        _.assign(metaData[value], {
                            dimensions: {
                                width: key.width,
                                height: key.height
                            }
                        });
                    }
                }
            });

            return metaData;
        });
}
1242180
async def updateImageMetadata(self):
    
    assert(self.needMetadataUpdate())

    width_sum, height_sum = 0, 0

    # only download metadata for the needed images to get full size
    idxs = []
    assert(is_square(len(self.urls)))
    sq = int(math.sqrt(len(self.urls)))
    for x in range(sq):
      for y in range(sq):
        if x == y:
          idxs.append((x * sq + y, x, y))

    for idx, x, y in idxs:
      url = self.urls[idx]
      format, width, height = None, None, None

      try:
        format, width, height = pickle.loads(__class__.metadata_cache[url])
      except KeyError:
        # cache miss
        pass
      except Exception as e:
        logging.getLogger("Cover").warning("Unable to load metadata for URL '%s' from cache: %s %s" % (url,
                                                                                                       e.__class__.__qualname__,
                                                                                                       e))
      else:
        # cache hit
        logging.getLogger("Cover").debug("Got metadata for URL '%s' from cache" % (url))
        if format is not None:
          self.setFormatMetadata(format)

      if (self.needMetadataUpdate(CoverImageMetadata.FORMAT) or
              (self.needMetadataUpdate(CoverImageMetadata.SIZE) and ((width is None) or (height is None)))):
        # download
        logging.getLogger("Cover").debug("Downloading file header for URL '%s'..." % (url))
        try:
          headers = {}
          self.source.updateHttpHeaders(headers)
          response = await self.source.http.fastStreamedQuery(url,
                                                              headers=headers,
                                                              verify=False)
          try:
            if self.needMetadataUpdate(CoverImageMetadata.FORMAT):
              # try to get format from response
              format = __class__.guessImageFormatFromHttpResponse(response)
              if format is not None:
                self.setFormatMetadata(format)

            if self.needMetadataUpdate():
              # try to get metadata from HTTP data
              metadata = await __class__.guessImageMetadataFromHttpData(response)
              if metadata is not None:
                format, width, height = metadata
                if format is not None:
                  self.setFormatMetadata(format)

          finally:
            response.release()

        except Exception as e:
          logging.getLogger("Cover").warning("Failed to get file metadata for URL '%s' "
                                             "(%s %s)" % (url,
                                                          e.__class__.__qualname__,
                                                          e))

        if self.needMetadataUpdate():  # did we fail to get needed metadata at this point?
          if ((self.format is None) or
                  ((self.size is None) and ((width is None) or (height is None)))):
            # if we get here, file is probably not reachable, or not even an image
            logging.getLogger("Cover").debug("Unable to get file metadata from file or HTTP headers for URL '%s', "
                                             "skipping this result" % (url))
            return

          if ((self.format is not None) and
                  ((self.size is not None) and (width is None) and (height is None))):
            logging.getLogger("Cover").debug("Unable to get file metadata from file or HTTP headers for URL '%s', "
                                             "falling back to API data" % (url))
            self.check_metadata = CoverImageMetadata.NONE
            self.reliable_metadata = False
            return

        # save it to cache
        __class__.metadata_cache[url] = pickle.dumps((format, width, height))

      # sum sizes
      if (width is not None) and (height is not None):
        width_sum += width
        height_sum += height

    if self.needMetadataUpdate(CoverImageMetadata.SIZE) and (width_sum > 0) and (height_sum > 0):
      self.setSizeMetadata((width_sum, height_sum))
1207261
function getMetadata (dir) {
  var json = path.join(dir, 'meta.json')
  var js = path.join(dir, 'meta.js')
  var opts = {}

  if (exists(json)) {
    opts = metadata.sync(json)
  } else if (exists(js)) {
    var req = require(path.resolve(js))
    if (req !== Object(req)) {
      throw new Error('meta.js needs to expose an object')
    }
    opts = req
  }

  return opts
}
819416
function getDimensions(el, which) {
        switch (which) {
        case 'height':
            return  getStyle(el, "marginTop")        +
                    getStyle(el, "marginBottom")     +
                    getStyle(el, "paddingTop")       +
                    getStyle(el, "paddingBottom")    +
                    getStyle(el, "borderTopWidth")   +
                    getStyle(el, "borderBottomWidth");
        case 'width':
            return   getStyle(el, "marginLeft")      +
                     getStyle(el, "marginRight")     +
                     getStyle(el, "paddingLeft")     +
                     getStyle(el, "paddingRight")    +
                     getStyle(el, "borderLeftWidth") +
                     getStyle(el, "borderRightWidth");
        default:
            break;
        }

        return getStyle(el, which);
    }
554942
def get_image_tags(instance):
    
    if hasattr(instance, 'image') and hasattr(instance.image, 'exif'):
        aspect_ratio = compute_aspect_ratio(instance.image)
    elif 'image' in instance.glossary and 'width' in instance.glossary['image']: 
        aspect_ratio = compute_aspect_ratio_with_glossary(instance.glossary)
        instance.glossary['ramdom_svg_color'] = 'hsl({}, 30%, 80%, 0.8)'.format( str(random.randint(0, 360)))
    else:
        # if accessing the image file fails or fake image fails, abort here
        logger.warning("Unable to compute aspect ratio of image '{}'".format(instance.image))
        return

    is_responsive = 'img-fluid' in instance.glossary.get('image_shapes', [])
    resize_options = instance.glossary.get('resize_options', {})
    crop = 'crop' in resize_options
    upscale = 'upscale' in resize_options
    if 'subject_location' in resize_options and hasattr(instance.image, 'subject_location'):
        subject_location = instance.image.subject_location
    else:
        subject_location = None
    tags = {'sizes': [], 'srcsets': {}, 'is_responsive': is_responsive, 'extra_styles': {}}
    if is_responsive:
        image_width = parse_responsive_length(instance.glossary.get('image_width_responsive') or '100%')
        assert(image_width[1]), "The given image has no valid width"
        if image_width[1] != 1.0:
            tags['extra_styles'].update({'max-width': '{:.0f}%'.format(100 * image_width[1])})
    else:
        image_width = parse_responsive_length(instance.glossary['image_width_fixed'])
        if not image_width[0]:
            image_width = (instance.image.width, image_width[1])
    try:
        image_height = parse_responsive_length(instance.glossary['image_height'])
    except KeyError:
        image_height = (None, None)
    if is_responsive:
        column_bounds_min = instance.glossary['column_bounds']['min']
        if 'high_resolution' in resize_options:
            column_bounds_max = 2 * instance.glossary['column_bounds']['max']
        else:
            column_bounds_max = instance.glossary['column_bounds']['max']
        num_steps = min(int((column_bounds_max - column_bounds_min) / app_settings.RESPONSIVE_IMAGE_STEP_SIZE),
                        app_settings.RESPONSIVE_IMAGE_MAX_STEPS)
        step_width, max_width = (column_bounds_max - column_bounds_min) / num_steps, 0
        for step in range(0, num_steps + 1):
            width = round(column_bounds_min + step_width * step)
            max_width = max(max_width, width)
            size = get_image_size(width, image_height, aspect_ratio)
            key = '{0}w'.format(*size)
            tags['srcsets'][key] = {'size': size, 'crop': crop, 'upscale': upscale,
                                    'subject_location': subject_location}
        tags['sizes'] = instance.glossary['media_queries'].values()
        # use an existing image as fallback for the <img ...> element
        if not max_width > 0:
            logger.warning('image tags: image max width is zero')
        size = (int(round(max_width)), int(round(max_width * aspect_ratio)))
    else:
        size = get_image_size(image_width[0], image_height, aspect_ratio)
        if 'high_resolution' in resize_options:
            tags['srcsets']['1x'] = {'size': size, 'crop': crop, 'upscale': upscale,
                                     'subject_location': subject_location}
            tags['srcsets']['2x'] = dict(tags['srcsets']['1x'], size=(size[0] * 2, size[1] * 2))
    tags['src'] = {'size': size, 'crop': crop, 'upscale': upscale, 'subject_location': subject_location}
    return tags
328129
function extractMetadata (content, callback) {
  var end;
  var result;
  var metadata = '';
  var body = content;

  // Metadata is defined by either starting and ending line,
  if (content.slice(0, 3) === '---') {
    result = content.match(/^-{3,}\s([\s\S]*?)-{3,}(\s[\s\S]*|\s?)$/);
    if (result && result.length === 3) {
      metadata = result[1];
      body = result[2];
    }
  }
  // or Markdown metadata section at beginning of file.
  else if (content.slice(0, 12) === '```metadata\n') {
    end = content.indexOf('\n```\n');
    if (end !== -1) {
      metadata = content.substring(12, end);
      body = content.substring(end + 5);
    }
  }

  parseMetadata(metadata, function (error, parsed) {
    if (error) return callback(error);
    callback(null, {
      metadata: parsed,
      body: body
    });
  });
}
647279
async def guessImageMetadataFromHttpData(response):
    
    metadata = None
    img_data = bytearray()

    while len(img_data) < CoverSourceResult.MAX_FILE_METADATA_PEEK_SIZE:
      new_img_data = await response.content.read(__class__.METADATA_PEEK_SIZE_INCREMENT)
      if not new_img_data:
        break
      img_data.extend(new_img_data)

      metadata = __class__.guessImageMetadataFromData(img_data)
      if (metadata is not None) and all(metadata):
        return metadata

    return metadata
325273
def set_image_dimensions(self, thumbnail):
        
        try:
            dimensions = getattr(thumbnail, 'dimensions', None)
        except models.ThumbnailDimensions.DoesNotExist:
            dimensions = None
        if not dimensions:
            return False
        self._dimensions_cache = dimensions.size
        return self._dimensions_cache
704386
public function getDefaultImageResizeWidth()
    {
        if ($width = $this->owner->ImageDefaultResizeWidth) {
            return $width;
        }
        
        if ($this->owner->hasExtension(MetaDataExtension::class)) {
            return $this->owner->getFieldFromParent('DefaultImageResizeWidth');
        }
    }
195208
def extract_image_size(self):
        '''
        
        '''
        width, _ = self._extract_alternative_fields(
            ['Image ImageWidth', 'EXIF ExifImageWidth'], -1, int)
        height, _ = self._extract_alternative_fields(
            ['Image ImageLength', 'EXIF ExifImageLength'], -1, int)
        return width, height
424810
private ImageryMetaDataResource getMetaData() {
        Log.d(IMapView.LOGTAG, "getMetaData");

        ImageryMetaDataResource returnValue = null;

        InputStream in = null;
        HttpURLConnection client = null;
        ByteArrayOutputStream dataStream = null;
        BufferedOutputStream out = null;
        try {
            client = (HttpURLConnection) (new URL(String.format(BASE_URL_PATTERN, mStyle, mBingMapKey)).openConnection());
            Log.d(IMapView.LOGTAG, "make request " + client.getURL().toString().toString());
            client.setRequestProperty(Configuration.getInstance().getUserAgentHttpHeader(), Configuration.getInstance().getUserAgentValue());
            for (final Map.Entry<String, String> entry : Configuration.getInstance().getAdditionalHttpRequestProperties().entrySet()) {
                client.setRequestProperty(entry.getKey(), entry.getValue());
            }
            client.connect();

            if (client.getResponseCode() != 200) {
                Log.e(IMapView.LOGTAG, "Cannot get response for url " + client.getURL().toString() + " " + client.getResponseMessage());

            } else {

                in = client.getInputStream();
                dataStream = new ByteArrayOutputStream();
                out = new BufferedOutputStream(dataStream, StreamUtils.IO_BUFFER_SIZE);
                StreamUtils.copy(in, out);
                out.flush();

                returnValue = ImageryMetaData.getInstanceFromJSON(dataStream.toString());
            }
        } catch (final Exception e) {
            Log.e(IMapView.LOGTAG, "Error getting imagery meta data", e);
        } finally {
            if (client != null)
                try {
                    client.disconnect();
                } catch (Exception e) {
                    Log.d(IMapView.LOGTAG, "end getMetaData", e);
                }
            if (in != null)
                try {
                    in.close();
                } catch (Exception e) {
                    Log.d(IMapView.LOGTAG, "end getMetaData", e);
                }
            if (dataStream != null)
                try {
                    dataStream.close();
                } catch (Exception e) {
                    Log.d(IMapView.LOGTAG, "end getMetaData", e);
                }
            if (out != null)
                try {
                    out.close();
                } catch (Exception e) {
                    Log.d(IMapView.LOGTAG, "end getMetaData", e);
                }
            Log.d(IMapView.LOGTAG, "end getMetaData");
        }
        return returnValue;
    }
549542
function resizeImage(ctx, imageData, width, height) {
  const {naturalWidth, naturalHeight} = imageData;
  if (width === naturalWidth && height === naturalHeight) {
    return imageData;
  }

  ctx.canvas.height = height;
  ctx.canvas.width = width;

  ctx.clearRect(0, 0, ctx.canvas.width, ctx.canvas.height);

  // image, sx, sy, sWidth, sHeight, dx, dy, dWidth, dHeight
  ctx.drawImage(imageData, 0, 0, naturalWidth, naturalHeight, 0, 0, width, height);

  return ctx.canvas;
}
1279819
function dimensions(el, width, height) {
        var el_width = Embedo.utils.compute(el, 'width');
        width = width ?
          width :
          el_width > 0 ?
          el_width :
          Embedo.utils.compute(el.parentNode, 'width');
        height = height ?
          height :
          el_width > 0 ?
          el_width / 1.5 :
          Embedo.utils.compute(el.parentNode, 'height');
        return {
          width: width,
          height: height
        };
      }
1264576
private Dimension getRequestedDimension() {

    // check for fixed dimensions from media args
    if (mediaArgs.getFixedWidth() > 0 || mediaArgs.getFixedHeight() > 0) {
      return new Dimension(mediaArgs.getFixedWidth(), mediaArgs.getFixedHeight());
    }

    // check for dimensions from mediaformat (evaluate only first media format)
    MediaFormat[] mediaFormats = mediaArgs.getMediaFormats();
    if (mediaFormats != null && mediaFormats.length > 0) {
      Dimension dimension = mediaFormats[0].getMinDimension();
      if (dimension != null) {
        return dimension;
      }
    }

    // fallback to 0/0 - no specific dimension requested
    return new Dimension(0, 0);
  }
374866
function getImageData (canvasId, x, y, width, height, done) {
  wx.canvasGetImageData({
    canvasId,
    x,
    y,
    width,
    height,
    success (res) {
      done(res, null)
    },
    fail (res) {
      done(null, res)
    }
  })
}
746099
function ImageInfoRequest(env, filename, dims, key) {
	ApiRequest.call(this, env, null);
	this.env = env;
	this.queueKey = key;
	this.reqType = "Image Info Request";

	var conf = env.conf.wiki;
	var filenames = [ filename ];
	var imgnsid = conf.canonicalNamespaces.image;
	var imgns = conf.namespaceNames[imgnsid];
	var props = [
		'mediatype',
		'mime',
		'size',
		'url',
		'badfile',
	];

	// If the videoinfo prop is available, as determined by our feature
	// detection when initializing the wiki config, use that to fetch the
	// derivates for videos.  videoinfo is just a wrapper for imageinfo,
	// so all our media requests should go there, and the response can be
	// disambiguated by the returned mediatype.
	var prop, prefix;
	if (conf.useVideoInfo) {
		prop = 'videoinfo';
		prefix = 'vi';
		props.push('derivatives', 'timedtext');
	} else {
		prop = 'imageinfo';
		prefix = 'ii';
	}

	this.ns = imgns;

	for (var ix = 0; ix < filenames.length; ix++) {
		filenames[ix] = imgns + ':' + filenames[ix];
	}

	var apiArgs = {
		action: 'query',
		format: 'json',
		formatversion: 2,
		prop: prop,
		titles: filenames.join('|'),
		rawcontinue: 1,
	};

	apiArgs[prefix + 'prop'] = props.join('|');
	apiArgs[prefix + 'badfilecontexttitle'] = env.page.name;

	if (dims) {
		if (dims.width !== undefined && dims.width !== null) {
			console.assert(typeof (dims.width) === 'number');
			apiArgs[prefix + 'urlwidth'] = dims.width;
			if (dims.page !== undefined) {
				// NOTE: This format is specific to PDFs.  Not sure how to
				// support this generally, though it seems common enough /
				// shared with other file types.
				apiArgs[prefix + 'urlparam'] = `page${dims.page}-${dims.width}px`;
			}
		}
		if (dims.height !== undefined && dims.height !== null) {
			console.assert(typeof (dims.height) === 'number');
			apiArgs[prefix + 'urlheight'] = dims.height;
		}
		if (dims.seek !== undefined) {
			apiArgs[prefix + 'urlparam'] = `seek=${dims.seek}`;
		}
	}

	this.requestOptions = {
		method: 'GET',
		followRedirect: true,
		uri: env.conf.wiki.apiURI,
		qs: apiArgs,
		timeout: env.conf.parsoid.timeouts.mwApi.imgInfo,
	};

	this.request(this.requestOptions);
}
1020177
def get_metadata(self, digest, content, mime_type):
        """"""

        # XXX: ad-hoc for now, refactor later
        if mime_type.startswith("image/"):
            img = Image.open(BytesIO(content))
            ret = {}
            if not hasattr(img, "_getexif"):
                return {}
            info = img._getexif()
            if not info:
                return {}
            for tag, value in info.items():
                decoded = TAGS.get(tag, tag)
                ret["EXIF:" + str(decoded)] = value
            return ret
        else:
            if mime_type != "application/pdf":
                content = self.to_pdf(digest, content, mime_type)

            with make_temp_file(content) as in_fn:
                try:
                    output = subprocess.check_output(["pdfinfo", in_fn])
                except OSError:
                    logger.error("Conversion failed, probably pdfinfo is not installed")
                    raise

            ret = {}
            for line in output.split(b"\n"):
                if b":" in line:
                    key, value = line.strip().split(b":", 1)
                    key = str(key)
                    ret["PDF:" + key] = str(value.strip(), errors="replace")

            return ret