Return (width, height) for a given img file content
    no requirements
10187
def getDPI(filepath):
    
    xDPI = -1
    yDPI = -1
    with open(filepath, 'rb') as fhandle:
        head = fhandle.read(24)
        size = len(head)
        # handle GIFs
        # GIFs doesn't have density
        if size >= 10 and head[:6] in (b'GIF87a', b'GIF89a'):
            pass
        # see png edition spec bytes are below chunk length then and finally the
        elif size >= 24 and head.startswith(b'\211PNG\r\n\032\n'):
            chunkOffset = 8
            chunk = head[8:]
            while True:
                chunkType = chunk[4:8]
                if chunkType == b'pHYs':
                    try:
                        xDensity, yDensity, unit = struct.unpack(">LLB", chunk[8:])
                    except struct.error:
                        raise ValueError("Invalid PNG file")
                    if unit:
                        xDPI = _convertToDPI(xDensity, _UNIT_1M)
                        yDPI = _convertToDPI(yDensity, _UNIT_1M)
                    else:  # no unit
                        xDPI = xDensity
                        yDPI = yDensity
                    break
                elif chunkType == b'IDAT':
                    break
                else:
                    try:
                        dataSize, = struct.unpack(">L", chunk[0:4])
                    except struct.error:
                        raise ValueError("Invalid PNG file")
                    chunkOffset += dataSize + 12
                    fhandle.seek(chunkOffset)
                    chunk = fhandle.read(17)
        # handle JPEGs
        elif size >= 2 and head.startswith(b'\377\330'):
            try:
                fhandle.seek(0)  # Read 0xff next
                size = 2
                ftype = 0
                while not 0xc0 <= ftype <= 0xcf:
                    if ftype == 0xe0:  # APP0 marker
                        fhandle.seek(7, 1)
                        unit, xDensity, yDensity = struct.unpack(">BHH", fhandle.read(5))
                        if unit == 1 or unit == 0:
                            xDPI = xDensity
                            yDPI = yDensity
                        elif unit == 2:
                            xDPI = _convertToDPI(xDensity, _UNIT_CM)
                            yDPI = _convertToDPI(yDensity, _UNIT_CM)
                        break
                    fhandle.seek(size, 1)
                    byte = fhandle.read(1)
                    while ord(byte) == 0xff:
                        byte = fhandle.read(1)
                    ftype = ord(byte)
                    size = struct.unpack('>H', fhandle.read(2))[0] - 2
            except struct.error:
                raise ValueError("Invalid JPEG file")
        # handle JPEG2000s
        elif size >= 12 and head.startswith(b'\x00\x00\x00\x0cjP  \r\n\x87\n'):
            fhandle.seek(32)
            # skip JP2 image header box
            headerSize = struct.unpack('>L', fhandle.read(4))[0] - 8
            fhandle.seek(4, 1)
            foundResBox = False
            try:
                while headerSize > 0:
                    print("headerSize", headerSize)
                    boxHeader = fhandle.read(8)
                    boxType = boxHeader[4:]
                    print(boxType)
                    if boxType == 'res ':  # find resolution super box
                        foundResBox = True
                        headerSize -= 8
                        print("found res super box")
                        break
                    print("@1", boxHeader)
                    boxSize, = struct.unpack('>L', boxHeader[:4])
                    print("boxSize", boxSize)
                    fhandle.seek(boxSize - 8, 1)
                    headerSize -= boxSize
                if foundResBox:
                    while headerSize > 0:
                        boxHeader = fhandle.read(8)
                        boxType = boxHeader[4:]
                        print(boxType)
                        if boxType == 'resd':  # Display resolution box
                            print("@2")
                            yDensity, xDensity, yUnit, xUnit = struct.unpack(">HHBB", fhandle.read(10))
                            xDPI = _convertToDPI(xDensity, xUnit)
                            yDPI = _convertToDPI(yDensity, yUnit)
                            break
                        boxSize, = struct.unpack('>L', boxHeader[:4])
                        print("boxSize", boxSize)
                        fhandle.seek(boxSize - 8, 1)
                        headerSize -= boxSize
            except struct.error as e:
                print(e)
                raise ValueError("Invalid JPEG2000 file")
    return xDPI, yDPI
423110
private static function getImageSize($img)
    {
        $width  = imagesx($img);
        $height = imagesy($img);
        if ( ! $width || ! $height) {
            throw new \Exception('can`t create thumbnail: can`t get image size, invalid image width or height');
        }

        return [$width, $height];
    }
220207
function getImageNaturalSizes(image, callback) {
  var newImage = document.createElement('img');

  // Modern browsers (except Safari)
  if (image.naturalWidth && !IS_SAFARI) {
    callback(image.naturalWidth, image.naturalHeight);
    return newImage;
  }

  var body = document.body || document.documentElement;

  newImage.onload = function () {
    callback(newImage.width, newImage.height);

    if (!IS_SAFARI) {
      body.removeChild(newImage);
    }
  };

  newImage.src = image.src;

  // iOS Safari will convert the image automatically
  // with its orientation once append it into DOM
  if (!IS_SAFARI) {
    newImage.style.cssText = 'left:0;' + 'max-height:none!important;' + 'max-width:none!important;' + 'min-height:0!important;' + 'min-width:0!important;' + 'opacity:0;' + 'position:absolute;' + 'top:0;' + 'z-index:-1;';
    body.appendChild(newImage);
  }

  return newImage;
}
1170518
def img(self):
        ''''''
        import wx
        with warnings.catch_warnings():
            warnings.simplefilter('ignore')
            img = wx.EmptyImage(self.width, self.height)
            img.SetData(self.imgstr)
        return img
436775
function(url, img) {
        var svgImage = document.createElementNS(SVG_NS_URL, 'image');
        svgImage.setAttributeNS(XLINK_NS_URL, 'xlink:href', url);
        svgImage.setAttribute('x', 0);
        svgImage.setAttribute('y', 0);
        svgImage.setAttribute('width', img.width);
        svgImage.setAttribute('height', img.height);
        return svgImage;
      }
684192
def _get_image_size(self, maxcharno, maxlineno):
        
        return (self._get_char_x(maxcharno) + self.image_pad,
                self._get_line_y(maxlineno + 0) + self.image_pad)
767387
function (src, x, y, width, height) {
		var attribs = {
				preserveAspectRatio: NONE
			},
			elemWrapper;

		// optional properties
		if (arguments.length > 1) {
			extend(attribs, {
				x: x,
				y: y,
				width: width,
				height: height
			});
		}

		elemWrapper = this.createElement('image').attr(attribs);

		// set the href in the xlink namespace
		if (elemWrapper.element.setAttributeNS) {
			elemWrapper.element.setAttributeNS('http://www.w3.org/1999/xlink',
				'href', src);
		} else {
			// could be exporting in IE
			// using href throws "not supported" in ie7 and under, requries regex shim to fix later
			elemWrapper.element.setAttribute('hc-svg-href', src);
	}

		return elemWrapper;
	}
434935
def get_file(path=None, content=None):
    
    if path is None:
        path = request.args.get('path')

    if path is None:
        return error('No path in request')
    
    filename = os.path.split(path.rstrip('/'))[-1]
    extension = filename.rsplit('.', 1)[-1]
    os_file_path = web_path_to_os_path(path)

    if os.path.isdir(os_file_path):
        file_type = 'folder'
        # Ensure trailing slash
        if path[-1] != '/':
            path += '/'
    else:
        file_type = 'file'

    ctime = int(os.path.getctime(os_file_path))
    mtime = int(os.path.getmtime(os_file_path))

    height = 0
    width = 0
    if extension in ['gif', 'jpg', 'jpeg', 'png']:
        try:
            im = PIL.Image.open(os_file_path)
            height, width = im.size
        except OSError:
            log.exception('Error loading image "{}" to get width and height'.format(os_file_path))
    
    attributes = {
        'name': filename,
        'path': get_url_path(path),
        'readable': 1 if os.access(os_file_path, os.R_OK) else 0,
        'writeable': 1 if os.access(os_file_path, os.W_OK) else 0,
        'created': datetime.datetime.fromtimestamp(ctime).ctime(),
        'modified': datetime.datetime.fromtimestamp(mtime).ctime(),
        'timestamp': mtime,
        'width': width,
        'height': height,
        'size': os.path.getsize(os_file_path)
    }

    if content:
        attributes['content'] = content

    return {
        'id': path,
        'type': file_type,
        'attributes': attributes
    }
635390
def database_get_image_dimensions(file, close=False, dimensions=None):
    
    storage_hash = utils.get_storage_hash(file.storage)
    dimensions = None
    dimensions_cache = None
    try:
        thumbnail = models.Thumbnail.objects.select_related('dimensions').get(
            storage_hash=storage_hash, name=file.name)
    except models.Thumbnail.DoesNotExist:
        thumbnail = None
    else:
        try:
            dimensions_cache = thumbnail.dimensions
        except models.ThumbnailDimensions.DoesNotExist:
            dimensions_cache = None
        if dimensions_cache:
            return dimensions_cache.width, dimensions_cache.height
    dimensions = get_image_dimensions(file, close=close)
    if settings.THUMBNAIL_CACHE_DIMENSIONS and thumbnail:
        # Using get_or_create in case dimensions were created
        # while running get_image_dimensions.
        models.ThumbnailDimensions.objects.get_or_create(
            thumbnail=thumbnail,
            defaults={'width': dimensions[0], 'height': dimensions[1]})
    return dimensions
414031
def smart_fit(image, fit_to_width, fit_to_height):
        
        im_width, im_height = image.size
        out_width, out_height = fit_to_width, fit_to_height
        if im_width == 0 or im_height == 0:
            return (fit_to_width, fit_to_height)

        w_scale = float(fit_to_width) / float(im_width)
        h_scale = float(fit_to_height) / float(im_height)
        if w_scale < h_scale:
            scale = float(fit_to_width) / float(im_width)
            out_height = int(round(scale * im_height))
        else:
            scale = float(fit_to_height) / float(im_height)
            out_width = int(round(scale * im_width))

        return out_width, out_height
877476
def dump_img(fname):
    
    img = Image.open(fname)
    width, _ = img.size
    txt = ''
    pixels = list(img.getdata())
    for col in range(width):
        txt += str(pixels[col:col+width])
    return txt
933315
function getTextImage(imageId) {
    const width = SIZE;
    const height = SIZE;

    const tokens = imageId.substring(12).split(':');
    const l = tokens[0];
    const bg = tokens[1];
    const pixelData = createTextPixelData(l, bg);

    function getPixelData() {
      return pixelData;
    }

    const image = {
      imageId,
      minPixelValue: 0,
      maxPixelValue: 257,
      slope: 1.0,
      intercept: 0,
      windowCenter: 127,
      windowWidth: 256,
      render: cs.renderGrayscaleImage,
      getPixelData,
      rows: height,
      columns: width,
      height,
      width,
      color: false,
      columnPixelSpacing: 1.0,
      rowPixelSpacing: 1.0,
      invert: false,
      sizeInBytes: width * height
    };

    return {
      promise: new Promise((resolve) => {
        resolve(image);
      }),
      cancelFn: undefined
    };
  }
717074
def read_image(img_spec, bkground_thresh, ensure_num_dim=3):
    """"""

    img = load_image_from_disk(img_spec)

    if not np.issubdtype(img.dtype, np.floating):
        img = img.astype('float32')

    if ensure_num_dim == 3:
        img = check_image_is_3d(img)
    elif ensure_num_dim == 4:
        img = check_image_is_4d(img)

    return threshold_image(img, bkground_thresh)
515394
function getImageSize(element) {
            var imageObj = url.parse(element.attribs.src),
                requestOptions,
                timeout = 3000;

            if (!validator.isURL(imageObj.href)) {
                // revert this element, do not show
                element.name = 'img';

                return enter();
            }

            // We need the user-agent, otherwise some https request may fail (e. g. cloudfare)
            requestOptions = {
                headers: {
                    'User-Agent': 'Mozilla/5.0 Safari/537.36'
                },
                timeout: timeout,
                encoding: null
            };

            return got(
                imageObj.href,
                requestOptions
            ).then(function (response) {
                try {
                    // Using the Buffer rather than an URL requires to use sizeOf synchronously.
                    // See https://github.com/image-size/image-size#asynchronous
                    var dimensions = sizeOf(response.body);

                    // CASE: `.ico` files might have multiple images and therefore multiple sizes.
                    // We return the largest size found (image-size default is the first size found)
                    if (dimensions.images) {
                        dimensions.width = _.maxBy(dimensions.images, function (w) {return w.width;}).width;
                        dimensions.height = _.maxBy(dimensions.images, function (h) {return h.height;}).height;
                    }

                    element.attribs.width = dimensions.width;
                    element.attribs.height = dimensions.height;

                    return getLayoutAttribute(element);
                } catch (err) {
                    // revert this element, do not show
                    element.name = 'img';
                    return enter();
                }
            }).catch(function () {
                // revert this element, do not show
                element.name = 'img';
                return enter();
            });
        }
463841
def get_image(self, img, is_train):
        """"""
        img_arr = mx.image.imread(img)
        img_arr = transform(img_arr, 256, 256, is_train, self.boxes[img])
        return img_arr
336206
def parse_size(image, size):
        
        bits = size.split("x")
        if image.size[0] == 0 or image.size[1] == 0:
            ratio = 1.0
        else:
            ratio = float(image.size[0]) / float(image.size[1])

        if len(bits) == 1 or not bits[1]:
            width = int(bits[0])
            height = int(1 / ratio * width)
        elif not bits[0]:
            height = int(bits[1])
            width = int(height * ratio)
        else:
            width, height = map(int, bits)
        return width, height
759026
def get_image(width, height=None, background_color="cccccc", random_background_color=False):
    
    return Image(
        url=placeholdit.get_url(
            width,
            height=height,
            background_color=background_color,
            random_background_color=random_background_color
        ),
        credit="This is not an image credit",
        caption="This is not a caption"
    )