Function for insert image
772973
function callImage( $info )
    {
        $params = array();
        $leftMargin = false;
        $rightMargin = false;

        eZPDFTable::extractParameters( $info['p'], 0, $params, true );

        $filename = rawurldecode( $params['src'] );

        $mimetype = eZMimeType::findByFileContents( $filename );

        $this->transaction( 'start' );

        if ( !isset( $params['static'] ) )
        {
            $params['static'] = false;
        }

        if ( $this->yOffset()-$params['height'] < $this->ez['bottomMargin'] )
        {
            $this->ezNewPage();
        }

        if ( isset( $params['dpi'] ) )
        {
            $newWidth = (int)( $params['width'] * ( (int)$params['dpi'] / 72 ) );
            $newHeight = (int)( $params['height'] * ( (int)$params['dpi'] / 72 ) );
            $newFilename = eZSys::cacheDirectory() . '/' . md5( mt_rand() ) . '.jpg';
            while( file_exists( $newFilename ) )
            {
                $newFilename = eZSys::cacheDirectory() . '/' . md5( mt_rand() ) . '.jpg';
            }

            $img = eZImageManager::factory();
            $newImg = $img->convert( $filename,
                                     $newFilename,
                                     false,
                                     array( 'filters' => array( array( 'name' => 'geometry/scaledownonly',
                                                                       'data' => array( $newWidth, $newHeight ) ) ) ) );
            $filename = $newFilename['url'];
        }

        $drawableAreaWidth = $this->ez['pageWidth'] - $this->ez['leftMargin'] - $this->ez['rightMargin'];

        switch( $params['align'] )
        {
            case 'right':
            {
                $xOffset = $this->ez['pageWidth'] - ( $this->rightMargin() + $params['width'] );
                $rightMargin = $this->rightMargin() + $params['width'];
                if ( $rightMargin > ( $drawableAreaWidth + $this->rightMargin() ) )
                {
                    // the image is equal or larger then width of the page(of the drawable area) => no point
                    // to set $rightMargin and next object(text, image, ...) should be outputted below the image.
                    $rightMargin = false;
                }
            } break;

            case 'center':
            {
                $xOffset = ( $this->ez['pageWidth'] - $this->rightMargin() - $this->leftMargin() ) / 2 + $this->leftMargin() - $params['width'] / 2;
            } break;

            case 'left':
            default:
            {
                $xOffset = $this->leftMargin();
                $leftMargin = $this->leftMargin() + $params['width'];
                if ( $leftMargin > ( $drawableAreaWidth + $this->leftMargin() ) )
                {
                    // the image is equal or larger then width of the page(of the drawable area) => no point
                    // to set $leftMargin and next object(text, image, ...) should be outputted below the image.
                    $leftMargin = false;
                }

            } break;
        }

        if ( isset( $params['x'] ) )
        {
            $xOffset = $params['x'];
            $leftMargin = false;
            $rightMargin = false;
        }

        $yOffset = $this->yOffset();
        $whileCount = 0;

        if ( $params['width'] < $drawableAreaWidth )
        {
            while ( $this->leftMargin( $yOffset ) > $xOffset &&
                    ++$whileCount < 100 )
            {
                $yOffset -= 10;
            }
        }

        $yOffset -= $params['height'];
        $yOffset += $this->lineHeight()/2;
        if ( isset( $params['y'] ) )
        {
            $yOffset = $params['y'];
        }

        if ( $leftMargin !== false )
        {
            $this->setLimitedLeftMargin( $yOffset - 7, $yOffset + $params['height'] + 7, $leftMargin + 7 );
        }
        if ( $rightMargin !== false )
        {
            $this->setLimitedRightMargin( $yOffset- 7, $yOffset + $params['height'] + 7, $rightMargin + 7 );
        }

        switch( $mimetype['name'] )
        {
            case 'image/gif':
            {
                $newFilename = eZSys::cacheDirectory() . '/' . md5( mt_rand() ) . '.jpg';
                while( file_exists( $newFilename ) )
                {
                    $newFilename = eZSys::cacheDirectory() . '/' . md5( mt_rand() ) . '.jpg';
                }
                $newMimetype = eZMimeType::findByURL( $newFilename );

                $img = eZImageManager::factory();
                $newImg = $img->convert( $mimetype,
                                         $newMimetype,
                                         false,
                                         array() );
                $this->addJpegFromFile( $newMimetype['url'],
                                        $xOffset,
                                        $yOffset,
                                        $params['width'],
                                        $params['height'] );
            } break;

            case 'image/jpeg':
            {
                $this->addJpegFromFile( $filename,
                                        $xOffset,
                                        $yOffset,
                                        $params['width'],
                                        $params['height'] );
            } break;

            case 'image/png':
            {
                if ( $this->addPngFromFile( $filename,
                                            $xOffset,
                                            $yOffset,
                                            $params['width'],
                                            $params['height'] ) === false )
                {
                    $this->transaction('abort');
                    return;
                }
            } break;

            default:
            {
                eZDebug::writeError( 'Unsupported image file type, '. $mimetype['name'], __METHOD__ );
                $this->transaction( 'abort' );
                return;
            } break;
        }

        $this->transaction( 'commit' );

        if ( !$leftMargin && !$rightMargin  && !$params['static'] )
        {
            $this->y -= $params['height'] + $this->lineHeight();
        }

        return array( 'y' => $params['height'] + $this->lineHeight() );
    }
3390
function (imagen, width, height, quality, type, ratio, centerCrop, resizeIf) {
    var deferred = $q.defer();
    var canvasElement = document.createElement('canvas');
    var imageElement = document.createElement('img');
    imageElement.setAttribute('style', 'visibility:hidden;position:fixed;z-index:-100000');
    document.body.appendChild(imageElement);

    imageElement.onload = function () {
      var imgWidth = imageElement.width, imgHeight = imageElement.height;
      imageElement.parentNode.removeChild(imageElement);
      if (resizeIf != null && resizeIf(imgWidth, imgHeight) === false) {
        deferred.reject('resizeIf');
        return;
      }
      try {
        if (ratio) {
          var ratioFloat = upload.ratioToFloat(ratio);
          var imgRatio = imgWidth / imgHeight;
          if (imgRatio < ratioFloat) {
            width = imgWidth;
            height = width / ratioFloat;
          } else {
            height = imgHeight;
            width = height * ratioFloat;
          }
        }
        if (!width) {
          width = imgWidth;
        }
        if (!height) {
          height = imgHeight;
        }
        var dimensions = calculateAspectRatioFit(imgWidth, imgHeight, width, height, centerCrop);
        canvasElement.width = Math.min(dimensions.width, width);
        canvasElement.height = Math.min(dimensions.height, height);
        var context = canvasElement.getContext('2d');
        context.drawImage(imageElement,
          Math.min(0, -dimensions.marginX / 2), Math.min(0, -dimensions.marginY / 2),
          dimensions.width, dimensions.height);
        deferred.resolve(canvasElement.toDataURL(type || 'image/WebP', quality || 0.934));
      } catch (e) {
        deferred.reject(e);
      }
    };
    imageElement.onerror = function () {
      imageElement.parentNode.removeChild(imageElement);
      deferred.reject();
    };
    imageElement.src = imagen;
    return deferred.promise;
  }
120959
function insertMultipart (doc, attachments, qs, callback) {
      if (typeof qs === 'string') {
        qs = { docName: qs }
      }
      qs = qs || {}

      const docName = qs.docName
      delete qs.docName

      doc = Object.assign({ _attachments: {} }, doc)

      const multipart = []

      attachments.forEach(function (att) {
        doc._attachments[att.name] = {
          follows: true,
          length: Buffer.isBuffer(att.data)
            ? att.data.length : Buffer.byteLength(att.data),
          /* jscs:disable requireCamelCaseOrUpperCaseIdentifiers */
          'content_type': att.content_type
        }
        multipart.push({ body: att.data })
      })

      multipart.unshift({
        'content-type': 'application/json',
        body: JSON.stringify(doc)
      })

      return relax({
        db: dbName,
        method: 'PUT',
        contentType: 'multipart/related',
        doc: docName,
        qs: qs,
        multipart: multipart
      }, callback)
    }
599536
def image(self, image, name):
        
        assert len(name.split(" ")) < 2, "Ensure that you don't have spaces in your variable name, use '_' instead."
        name = "image_" + name
        self.previous.append(name)
        if self.previous[-1] not in self.previous[:-1]:
            self.c.execute("""INSERT INTO {time_stamp_table} (
                              variable_name, variable_type
                              ) VALUES ('{variable}', '{type}')"""
                           .format(time_stamp_table=self.time_stamp, variable=name, type="image"))
        else:
            self.previous.pop()

        self.c.execute("""CREATE TABLE IF NOT EXISTS {variable_table_name} (
                          images BLOB, time VARCHAR
                          )""".format(variable_table_name=self.time_stamp + '_' + name))

        self.c.execute("""INSERT INTO {variable_table_name} (
                          images, time) VALUES ('{img}', '{time}'
                          )""".format(variable_table_name=self.time_stamp + '_' + name,
                                      img=sqlite3.Binary(np.array(image).tobytes()), time=datetime.datetime.now()))
        self.conn.commit()
1137487
function insertForeignToken(t, value, arg3, arg4) {
    // A <font> tag is an HTML font tag if it has a color, font, or size
    // attribute.  Otherwise we assume it is foreign content
    function isHTMLFont(attrs) {
      for(var i = 0, n = attrs.length; i < n; i++) {
        switch(attrs[i][0]) {
        case "color":
        case "face":
        case "size":
          return true;
        }
      }
      return false;
    }

    var current;

    switch(t) {
    case 1: // TEXT
      // If any non-space, non-nul characters
      if (frameset_ok && NONWSNONNUL.test(value))
        frameset_ok = false;
      if (textIncludesNUL) {
        value = value.replace(NULCHARS, "\uFFFD");
      }
      insertText(value);
      return;
    case 4: // COMMENT
      insertComment(value);
      return;
    case 5: // DOCTYPE
      // ignore it
      return;
    case 2: // TAG
      switch(value) {
      case "font":
        if (!isHTMLFont(arg3)) break;
        /* falls through */
      case "b":
      case "big":
      case "blockquote":
      case "body":
      case "br":
      case "center":
      case "code":
      case "dd":
      case "div":
      case "dl":
      case "dt":
      case "em":
      case "embed":
      case "h1":
      case "h2":
      case "h3":
      case "h4":
      case "h5":
      case "h6":
      case "head":
      case "hr":
      case "i":
      case "img":
      case "li":
      case "listing":
      case "menu":
      case "meta":
      case "nobr":
      case "ol":
      case "p":
      case "pre":
      case "ruby":
      case "s":
      case "small":
      case "span":
      case "strong":
      case "strike":
      case "sub":
      case "sup":
      case "table":
      case "tt":
      case "u":
      case "ul":
      case "var":
        if (fragment) {
          break;
        }
        do {
          stack.pop();
          current = stack.top;
        } while(current.namespaceURI !== NAMESPACE.HTML &&
            !isMathmlTextIntegrationPoint(current) &&
            !isHTMLIntegrationPoint(current));

        insertToken(t, value, arg3, arg4);  // reprocess
        return;
      }

      // Any other start tag case goes here
      current = (stack.elements.length===1 && fragment) ? fragmentContext :
        stack.top;
      if (current.namespaceURI === NAMESPACE.MATHML) {
        adjustMathMLAttributes(arg3);
      }
      else if (current.namespaceURI === NAMESPACE.SVG) {
        value = adjustSVGTagName(value);
        adjustSVGAttributes(arg3);
      }
      adjustForeignAttributes(arg3);

      insertForeignElement(value, arg3, current.namespaceURI);
      if (arg4) { // the self-closing flag
        if (value === 'script' && current.namespaceURI === NAMESPACE.SVG) {
          // XXX deal with SVG scripts here
        }
        stack.pop();
      }
      return;

    case 3: // ENDTAG
      current = stack.top;
      if (value === "script" &&
        current.namespaceURI === NAMESPACE.SVG &&
        current.localName === "script") {

        stack.pop();

        // XXX
        // Deal with SVG scripts here
      }
      else {
        // The any other end tag case
        var i = stack.elements.length-1;
        var node = stack.elements[i];
        for(;;) {
          if (node.localName.toLowerCase() === value) {
            stack.popElement(node);
            break;
          }
          node = stack.elements[--i];
          // If non-html, keep looping
          if (node.namespaceURI !== NAMESPACE.HTML)
            continue;
          // Otherwise process the end tag as html
          parser(t, value, arg3, arg4);
          break;
        }
      }
      return;
    }
  }
1019446
function(imageElement) {
			_readyCb = function() {
				try {
					var w = imageElement.width;
					var h = imageElement.height;
					var newImg = document.createElement('img');
					var ratio = (w / _w < h / _h) ? (w / _w) : (h / _h);
					newImg.setAttribute('src', imageElement.getAttribute('src'));
					newImg.height = (h / ratio);
					newImg.width = (w / ratio);
					_context.clearRect(0, 0, _w, _h);
					_context.drawImage(newImg, 0, 0, _w, _h);
					link.setIcon(_canvas);
				} catch(e) {
					throw 'Error setting image. Message: ' + e.message;
				}
			};
			if (_ready) {
				_readyCb();
			}
		}
1055220
function insert(elem) {
        try {
            $(exports).triggerHandler('insert', [elem]);
        } catch (err) {
            console.error(err);
        }
        var writer = new Writer();
        elem.save(writer);
        _currentOperation.ops.push({op: OP_INSERT, arg: writer.current});
    }
268254
def imgwriteincr(fn: Path, imgs, imgslice):
    
    if isinstance(imgslice, int):
        if imgslice and not (imgslice % 2000):
            print(f'appending images {imgslice} to {fn}')

    if isinstance(fn, Path):
        # avoid accidental overwriting of source file due to misspecified command line
        assert fn.suffix == '.h5', 'Expecting to write .h5 file'

        with h5py.File(fn, 'r+') as f:
            f['/rawimg'][imgslice, :, :] = imgs
    elif isinstance(fn, h5py.File):
        f['/rawimg'][imgslice, :, :] = imgs
    else:
        raise TypeError(
            f'{fn} must be Path or h5py.File instead of {type(fn)}')
1315830
def add_pic(self, post_data):
        '''
        
        '''
        img_entity = self.request.files['file'][0]
        filename = img_entity["filename"]

        if filename and allowed_file(filename):
            pass
        else:
            return False

        _, hou = os.path.splitext(filename)
        signature = str(uuid.uuid1())
        outfilename = '{0}{1}'.format(signature, hou)
        outpath = 'static/upload/{0}'.format(signature[:2])
        if os.path.exists(outpath):
            pass
        else:
            os.makedirs(outpath)
        with open(os.path.join(outpath, outfilename), "wb") as fileout:
            fileout.write(img_entity["body"])
        path_save = os.path.join(signature[:2], outfilename)
        sig_save = os.path.join(signature[:2], signature)

        imgpath = os.path.join(outpath, signature + '_m.jpg')
        imgpath_sm = os.path.join(outpath, signature + '_sm.jpg')

        ptr_image = Image.open(os.path.join('static/upload', path_save))
        tmpl_size = (768, 768)
        thub_size = (256, 256)
        (imgwidth, imgheight) = ptr_image.size
        if imgwidth < tmpl_size[0] and imgheight < tmpl_size[1]:
            tmpl_size = (imgwidth, imgheight)
        ptr_image.thumbnail(tmpl_size)

        im0 = ptr_image.convert('RGB')
        im0.save(imgpath, 'JPEG')

        im0.thumbnail(thub_size)
        im0.save(imgpath_sm, 'JPEG')

        create_pic = MEntity.create_entity(signature,
                                           path_save,
                                           post_data['desc'] if 'desc' in post_data else '',
                                           kind=post_data['kind'] if 'kind' in post_data else '1')
        if self.entity_ajax == False:
            self.redirect('/entity/{0}_m.jpg'.format(sig_save))
        else:
            if create_pic:
                output = {'path_save': imgpath}
            else:
                output = {'path_save': ''}
            return json.dump(output, self)
662955
def _insert_item(self, root, data, from_file=False):
        """"""

        tree = self.treeview
        treelabel = data.get_id()
        row = col = ''
        if root != '' and 'layout' in data:
            row = data.get_layout_property('row')
            col = data.get_layout_property('column')

            # fix row position when using copy and paste
            # If collision, increase by 1
            row_count = self.get_max_row(root)
            if not from_file and (row_count > int(row) and int(col) == 0):
                row = str(row_count + 1)
                data.set_layout_property('row', row)

        image = ''
        try:
            image = StockImage.get('16x16-tk.default')
        except StockImageException:
            # TODO: notify something here
            pass

        try:
            image = StockImage.get('16x16-{0}'.format(data.get_class()))
        except StockImageException:
            # TODO: notify something here
            pass

        values = (data.get_class(), row, col)
        item = tree.insert(root, 'end', text=treelabel, values=values,
                           image=image)
        data.attach(self)
        self.treedata[item] = data

        # Update grid r/c data
        self._update_max_grid_rc(root, from_file=True)
        self.app.set_changed()

        return item
19608
def image_function(template=None, entry=None, category=None):
    

    path = []

    if entry is not None:
        path += entry.search_path
    if category is not None:
        # Since the category might be different than the entry's category we add
        # this too
        path += category.search_path
    if template is not None:
        path.append(os.path.join(
            config.content_folder,
            os.path.dirname(template.filename)))

    return lambda filename: image.get_image(filename, path)
102517
function (src, x, y, width, height) {
		var obj = this.createElement('img')
			.attr({ src: src });

		if (arguments.length > 1) {
			obj.attr({
				x: x,
				y: y,
				width: width,
				height: height
			});
		}
		return obj;
	}
314542
def add_pic(self, id_, name, desc, rId, x, y, cx, cy):
        
        pic = CT_Picture.new_pic(id_, name, desc, rId, x, y, cx, cy)
        self.insert_element_before(pic, 'p:extLst')
        return pic
814328
function ()
    {
      // Append image label containers
      this.imageLabel = jQuery('<div/>', {'class': 'jBox-image-label-container'}).appendTo(this.wrapper);
      this.imageLabel.append(jQuery('<div/>', {'class': 'jBox-image-pointer-prev', click: function () { this.showImage('prev'); }.bind(this)})).append(jQuery('<div/>', {'class': 'jBox-image-pointer-next', click: function () { this.showImage('next'); }.bind(this)}));

      // Append the download button
      if (this.options.downloadButton) {
        this.downloadButton = jQuery('<div/>', {'class': 'jBox-image-download-button-wrapper'})
          .appendTo(this.wrapper)
          .append(
            this.options.downloadButtonText ? jQuery('<div/>', {'class': 'jBox-image-download-button-text'}).html(this.options.downloadButtonText) : null
          )
          .append(
            jQuery('<div/>', {'class': 'jBox-image-download-button-icon'})
          ).on('click touchdown', function () {
            if (this.images[this.currentImage.gallery][this.currentImage.id].downloadUrl) {
              var currentImageUrl = this.images[this.currentImage.gallery][this.currentImage.id].downloadUrl;
            } else {
              var currentImage = this.wrapper.find('.jBox-image-default-current');
              var currentImageStyle = currentImage[0].style.backgroundImage;
              var currentImageUrl = currentImageStyle.slice(4, -1).replace(/["']/g, '');
            }
            this.downloadImage(currentImageUrl);
          }.bind(this));
      }

      // Creating the image counter containers
      if (this.options.imageCounter) {
        this.imageCounter = jQuery('<div/>', {'class': 'jBox-image-counter-container'}).appendTo(this.wrapper);
        this.imageCounter.append(jQuery('<span/>', {'class': 'jBox-image-counter-current'})).append(jQuery('<span/>').html(this.options.imageCounterSeparator)).append(jQuery('<span/>', {'class': 'jBox-image-counter-all'}));
      }
    }
114260
function TexImage () {
    TexFlags.call(this)

    this.xOffset = 0
    this.yOffset = 0

    // data
    this.data = null
    this.needsFree = false

    // html element
    this.element = null

    // copyTexImage info
    this.needsCopy = false
  }
743933
function imageToCanvas(img) {
    var width = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : null;
    var height = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : null;

    if (!img.complete) {
      throw new Error('Can not create canvas from Image. Image is not loaded yet.');
    }
    var canvas = document.createElement("canvas");
    if (width === null && height === null) {
      canvas.width = img.naturalWidth;
      canvas.height = img.naturalHeight;
      canvas.getContext("2d").drawImage(img, 0, 0);
    } else {
      canvas.width = width;
      canvas.height = height;
      canvas.getContext("2d").drawImage(img, 0, 0, width, height);
    }
    return canvas;
  }
1224561
def process_image(self, decorator):
        
        savefig_dir = self.savefig_dir
        source_dir = self.source_dir
        saveargs = decorator.split(' ')
        filename = saveargs[1]
        # insert relative path to image file in source
        outfile = os.path.relpath(os.path.join(savefig_dir,filename),
                    source_dir)

        imagerows = ['.. image:: %s'%outfile]

        for kwarg in saveargs[2:]:
            arg, val = kwarg.split('=')
            arg = arg.strip()
            val = val.strip()
            imagerows.append('   :%s: %s'%(arg, val))

        image_file = os.path.basename(outfile) # only return file name
        image_directive = '\n'.join(imagerows)
        return image_file, image_directive