possible input params:
   IO      of opened image file
   String  with image file already readed
   Hash    of image parameters to create new blank image
760845
def inspect
      "#<ZPNG::Image " +
      %w'width height bpp chunks scanlines'.map do |k|
        v = case (v = send(k))
          when Array
            "[#{v.size} entries]"
          when String
            v.size > 40 ? "[#{v.bytesize} bytes]" : v.inspect
          else v.inspect
        end
        "#{k}=#{v}"
      end.compact.join(", ") + ">"
    end
992122
def parse_image_name(self, image):
        '''
             

        '''
        self._image = image
        self.uri = self.get_uri(image)
        self.image = self.remove_uri(image)
232129
def load_mime_types(file)
      open(file){ |io|
        hash = Hash.new
        io.each{ |line|
          next if /^#/ =~ line
          line.chomp!
          mimetype, ext0 = line.split(/\s+/, 2)
          next unless ext0
          next if ext0.empty?
          ext0.split(/\s+/).each{ |ext| hash[ext] = mimetype }
        }
        hash
      }
    end
77419
def encode_example(self, image_or_path_or_fobj):
    """"""
    if isinstance(image_or_path_or_fobj, np.ndarray):
      encoded_image = self._encode_image(image_or_path_or_fobj)
    elif isinstance(image_or_path_or_fobj, six.string_types):
      with tf.io.gfile.GFile(image_or_path_or_fobj, 'rb') as image_f:
        encoded_image = image_f.read()
    else:
      encoded_image = image_or_path_or_fobj.read()
    return encoded_image
322860
def _url_params(size:str='>400*300', format:str='jpg') -> str:
    ""
    _fmts = {'jpg':'ift:jpg','gif':'ift:gif','png':'ift:png','bmp':'ift:bmp', 'svg':'ift:svg','webp':'webp','ico':'ift:ico'}
    if size not in _img_sizes: 
        raise RuntimeError(f"""Unexpected size argument value: {size}.
                    See `widgets.image_downloader._img_sizes` for supported sizes.""") 
    if format not in _fmts: 
        raise RuntimeError(f"Unexpected image file format: {format}. Use jpg, gif, png, bmp, svg, webp, or ico.")
    return "&tbs=" + _img_sizes[size] + "," + _fmts[format]
1142532
def replace(input, **pars):
    
    pixvalue = pars.get('pixvalue', np.nan)
    if pixvalue is None: pixvalue = np.nan # insure that None == np.nan

    newvalue = pars.get('newvalue', 0.0)
    ext = pars.get('ext',None)
    if ext in ['',' ','None',None]:
        ext = None

    files = parseinput.parseinput(input)[0]

    for f in files:
        fimg = fits.open(f, mode='update', memmap=False)

        if ext is None:
            # replace pixels in ALL extensions
            extn = [i for i in fimg]
        else:
            if type(ext) == type([]):
                extn = [fimg[e] for e in ext]
            else:
                extn = [fimg[ext]]

        for e in extn:
            if e.data is not None and e.is_image: # ignore empty Primary HDUs
                print("Converting {}[{},{}] value of {} to {}".format(
                        f,e.name,e.ver,pixvalue,newvalue))
                if np.isnan(pixvalue):
                    e.data[np.isnan(e.data)] = newvalue
                else:
                    e.data[np.where(e.data == pixvalue)] = newvalue

        fimg.close()
413225
function(params, callback) {
                var fileName,
                    fileType,
                    fileSize,
                    fileExtension,
                    uploadUniqueId,
                    uploadThreadId;

                fileName = params.image.name;
                fileType = params.image.type;
                fileSize = params.image.size;
                fileExtension = params.image.name.split('.')
                    .pop();

                if (imageMimeTypes.indexOf(fileType) > 0 || imageExtentions.indexOf(fileExtension) > 0) {
                    uploadImageData = {};

                    if (params) {
                        if (typeof params.image !== 'undefined') {
                            uploadImageData.image = params.image;
                            uploadImageData.file = params.image;
                        }

                        if (typeof params.fileName == 'string') {
                            uploadImageData.fileName = params.fileName;
                        }
                        else {
                            uploadImageData.fileName = Utility.generateUUID() + '.' + fileExtension;
                        }

                        uploadImageData.fileSize = fileSize;

                        if (parseInt(params.threadId) > 0) {
                            uploadThreadId = params.threadId;
                            uploadImageData.threadId = params.threadId;
                        }
                        else {
                            uploadThreadId = 0;
                            uploadImageData.threadId = 0;
                        }

                        if (typeof params.uniqueId == 'string') {
                            uploadUniqueId = params.uniqueId;
                            uploadImageData.uniqueId = params.uniqueId;
                        }
                        else {
                            uploadUniqueId = Utility.generateUUID();
                            uploadImageData.uniqueId = uploadUniqueId;
                        }

                        if (typeof params.originalFileName == 'string') {
                            uploadImageData.originalFileName = params.originalFileName;
                        }
                        else {
                            uploadImageData.originalFileName = fileName;
                        }

                        if (parseInt(params.xC) > 0) {
                            uploadImageData.xC = params.xC;
                        }

                        if (parseInt(params.yC) > 0) {
                            uploadImageData.yC = params.yC;
                        }

                        if (parseInt(params.hC) > 0) {
                            uploadImageData.hC = params.hC;
                        }

                        if (parseInt(params.wC) > 0) {
                            uploadImageData.wC = params.wC;
                        }
                    }

                    httpRequest({
                        url: SERVICE_ADDRESSES.FILESERVER_ADDRESS + SERVICES_PATH.UPLOAD_IMAGE,
                        method: 'POST',
                        headers: {
                            '_token_': token,
                            '_token_issuer_': 1
                        },
                        data: uploadImageData,
                        uniqueId: uploadUniqueId
                    }, function(result) {
                        if (!result.hasError) {
                            try {
                                var response = (typeof result.result.responseText == 'string')
                                    ? JSON.parse(result.result.responseText)
                                    : result.result.responseText;
                                if (typeof response.hasError !== 'undefined' && !response.hasError) {
                                    callback({
                                        hasError: response.hasError,
                                        result: response.result
                                    });
                                }
                                else {
                                    callback({
                                        hasError: true,
                                        errorCode: response.errorCode,
                                        errorMessage: response.message
                                    });
                                }
                            }
                            catch (e) {
                                callback({
                                    hasError: true,
                                    errorCode: 6300,
                                    errorMessage: CHAT_ERRORS[6300]
                                });
                            }
                        }
                        else {
                            callback({
                                hasError: true,
                                errorCode: result.errorCode,
                                errorMessage: result.errorMessage
                            });
                        }
                    });

                    return {
                        uniqueId: uploadUniqueId,
                        threadId: uploadThreadId,
                        participant: userInfo,
                        content: {
                            caption: params.content,
                            file: {
                                uniqueId: uploadUniqueId,
                                fileName: fileName,
                                fileSize: fileSize,
                                fileObject: params.file
                            }
                        }
                    };
                }
                else {
                    callback({
                        hasError: true,
                        errorCode: 6301,
                        errorMessage: CHAT_ERRORS[6301]
                    });
                }
            }
1342610
def from_file(cls, image_descriptor):
        
        if is_string(image_descriptor):
            path = image_descriptor
            with open(path, 'rb') as f:
                blob = f.read()
                stream = BytesIO(blob)
            filename = os.path.basename(path)
        else:
            stream = image_descriptor
            stream.seek(0)
            blob = stream.read()
            filename = None
        return cls._from_stream(stream, blob, filename)
557483
def validate(self, instance, value):
        
        # Pass if already validated
        if getattr(value, '__valid__', False):
            return value
        # Validate that value is PNG
        if isinstance(value, png.Image):
            pass
        else:
            value = super(ImagePNG, self).validate(instance, value)
            try:
                png.Reader(value).validate_signature()
            except png.FormatError:
                self.error(instance, value, extra='Open file is not PNG.')
            value.seek(0)
        # Write input to new bytestream
        output = BytesIO()
        output.name = self.filename
        output.__valid__ = True
        if isinstance(value, png.Image):
            value.save(output)
        else:
            fid = value
            fid.seek(0)
            output.write(fid.read())
            fid.close()
        output.seek(0)
        return output
180765
def dummy_image(filetype='gif'):
    
    # 1x1px Transparent GIF
    GIF = 'R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7'
    tmp_file = tempfile.NamedTemporaryFile(suffix='.%s' % filetype)
    tmp_file.write(base64.b64decode(GIF))
    return open(tmp_file.name, 'rb')
1368846
def imread(filename, *args, **kwargs):
    
    try:
        netpbm = NetpbmFile(filename)
        image = netpbm.asarray()
    finally:
        netpbm.close()
    return image
857261
def image_name(image, key='name', clear=True):
    
    if hasattr(image, 'translation') and image.translation:
        return getattr(image.translation, key)

    if hasattr(image, key) and getattr(image, key):
        return getattr(image, key)

    try:
        name = IMAGE_NAME.match(image.original_filename).group()
    except IndexError:
        return ''
    else:
        name = name[:-1]
        if clear:
            return name.replace("_", " ").replace("-", " ")
        return name
84628
def get_image_hash(image):
    '''
    
    '''
    md5 = hashlib.md5()
    try:
        for chunk in image.file.chunks():
            md5.update(chunk)
        return md5.hexdigest()
    # this should only occur in tests
    except ValueError:
        # see link below for why we try not to use .open()
        # https://docs.djangoproject.com/en/1.9/ref/files/uploads/#django.core.files.uploadedfile.UploadedFile.chunks  # noqa
        image.file.open()

        for chunk in image.file.chunks():
            md5.update(chunk)
        return md5.hexdigest()
    finally:
        image.file.close()
505376
private void processParameters() throws BadElementException, IOException {
        type = JPEG;
        originalType = ORIGINAL_JPEG;
        InputStream is = null;
        try {
            String errorID;
            if (rawData == null){
                is = url.openStream();
                errorID = url.toString();
            }
            else{
                is = new java.io.ByteArrayInputStream(rawData);
                errorID = "Byte array";
            }
            if (is.read() != 0xFF || is.read() != 0xD8)	{
                throw new BadElementException(errorID + " is not a valid JPEG-file.");
            }
            boolean firstPass = true;
            int len;
            while (true) {
                int v = is.read();
                if (v < 0)
                    throw new IOException("Premature EOF while reading JPG.");
                if (v == 0xFF) {
                    int marker = is.read();
                    if (firstPass && marker == M_APP0) {
                        firstPass = false;
                        len = getShort(is);
                        if (len < 16) {
                            Utilities.skip(is, len - 2);
                            continue;
                        }
                        byte bcomp[] = new byte[JFIF_ID.length];
                        int r = is.read(bcomp);
                        if (r != bcomp.length)
                            throw new BadElementException(errorID + " corrupted JFIF marker.");
                        boolean found = true;
                        for (int k = 0; k < bcomp.length; ++k) {
                            if (bcomp[k] != JFIF_ID[k]) {
                                found = false;
                                break;
                            }
                        }
                        if (!found) {
                            Utilities.skip(is, len - 2 - bcomp.length);
                            continue;
                        }
                        Utilities.skip(is, 2);
                        int units = is.read();
                        int dx = getShort(is);
                        int dy = getShort(is);
                        if (units == 1) {
                            dpiX = dx;
                            dpiY = dy;
                        }
                        else if (units == 2) {
                            dpiX = (int)(dx * 2.54f + 0.5f);
                            dpiY = (int)(dy * 2.54f + 0.5f);
                        }
                        Utilities.skip(is, len - 2 - bcomp.length - 7);
                        continue;
                    }
                    if (marker == M_APPE) {
                        len = getShort(is) - 2;
                        byte[] byteappe = new byte[len];
                        for (int k = 0; k < len; ++k) {
                            byteappe[k] = (byte)is.read();
                        }
                        if (byteappe.length >= 12) {
                            String appe = new String(byteappe, 0, 5, "ISO-8859-1");
                            if (appe.equals("Adobe")) {
                                invert = true;
                            }
                        }
                        continue;
                    }
                    if (marker == M_APP2) {
                        len = getShort(is) - 2;
                        byte[] byteapp2 = new byte[len];
                        for (int k = 0; k < len; ++k) {
                            byteapp2[k] = (byte)is.read();
                        }
                        if (byteapp2.length >= 14) {
                            String app2 = new String(byteapp2, 0, 11, "ISO-8859-1");
                            if (app2.equals("ICC_PROFILE")) {
                                int order = byteapp2[12] & 0xff;
                                int count = byteapp2[13] & 0xff;
                                
                                // some jpeg producers don't know how to count to 1
                                if (order < 1) {
                                	order = 1;
                                }
                                if (count < 1) {
                                	count = 1;
                                }
                                if (icc == null){
                                    icc = new byte[count][];
                                }
                                int idx = order - 1;
                                if( idx >= 0 ) {
                                	icc[idx] = byteapp2;
                                }                                
                            }
                        }
                        continue;
                    }
                    firstPass = false;
                    int markertype = marker(marker);
                    if (markertype == VALID_MARKER) {
                        Utilities.skip(is, 2);
                        if (is.read() != 0x08) {
                            throw new BadElementException(errorID + " must have 8 bits per component.");
                        }
                        scaledHeight = getShort(is);
                        setTop(scaledHeight);
                        scaledWidth = getShort(is);
                        setRight(scaledWidth);
                        colorspace = is.read();
                        bpc = 8;
                        break;
                    }
                    else if (markertype == UNSUPPORTED_MARKER) {
                        throw new BadElementException(errorID + ": unsupported JPEG marker: " + marker);
                    }
                    else if (markertype != NOPARAM_MARKER) {
                        Utilities.skip(is, getShort(is) - 2);
                    }
                }
            }
        }
        finally {
            if (is != null) {
                is.close();
            }
        }
        plainWidth = getWidth();
        plainHeight = getHeight();
        if (icc != null) {
            int total = 0;
            for (int k = 0; k < icc.length; ++k) {
                if (icc[k] == null) {
                    icc = null;
                    return;
                }
                total += icc[k].length - 14;
            }
            byte[] ficc = new byte[total];
            total = 0;
            for (int k = 0; k < icc.length; ++k) {
                System.arraycopy(icc[k], 14, ficc, total, icc[k].length - 14);
                total += icc[k].length - 14;
            }
            try {
            	ICC_Profile icc_prof = ICC_Profile.getInstance(ficc);
            	tagICC(icc_prof);
            }
            catch(IllegalArgumentException e) {
            	// ignore ICC profile if it's invalid.
            }
            icc = null;
        }
    }
646240
def reveal(input_image: Union[str, IO[bytes]], encoding="UTF-8"):
    
    img = tools.open_image(input_image)
    width, height = img.size
    buff, count = 0, 0
    bitab = []
    limit = None
    for row in range(height):
        for col in range(width):

            # pixel = [r, g, b] or [r,g,b,a]
            pixel = img.getpixel((col, row))
            if img.mode == "RGBA":
                pixel = pixel[:3]  # ignore the alpha
            for color in pixel:
                buff += (color & 1) << (tools.ENCODINGS[encoding] - 1 - count)
                count += 1
                if count == tools.ENCODINGS[encoding]:
                    bitab.append(chr(buff))
                    buff, count = 0, 0
                    if bitab[-1] == ":" and limit is None:
                        try:
                            limit = int("".join(bitab[:-1]))
                        except:
                            pass

            if len(bitab) - len(str(limit)) - 1 == limit:
                img.close()
                return "".join(bitab)[len(str(limit)) + 1 :]
1022067
def createImageObjectList(files,instrpars,group=None,
                            undistort=True, inmemory=False):
    
    imageObjList = []
    mtflag = False
    mt_refimg = None
    for img in files:
        image = _getInputImage(img,group=group)
        image.setInstrumentParameters(instrpars)
        image.compute_wcslin(undistort=undistort)
        if 'MTFLAG' in image._image['PRIMARY'].header:
            # check to see whether we are dealing with moving target observations...
            _keyval = image._image['PRIMARY'].header['MTFLAG']
            if not util.is_blank(_keyval):
                if isinstance(_keyval,bool):
                    mtflag = _keyval
                else:
                    if 'T' in _keyval:
                        mtflag = True
                    else:
                        mtflag = False
        else:
            mtflag = False

        if mtflag:
            print("#####\nProcessing Moving Target Observations using reference image as WCS for all inputs!\n#####\n")
            if mt_refimg is None:
                mt_refimg = image
            else:
                image.set_mt_wcs(mt_refimg)
        image.inmemory = inmemory # set flag for inmemory processing
        # Now add (possibly updated) image object to list
        imageObjList.append(image)
    return imageObjList
184394
def get_image_details(self):
        '''
        
        '''
        if Image.objects.count() == 0:
            return None

        total = Image.objects.count()
        count = 1
        for local_image in Image.objects.all():
            if not hasattr(local_image, 'image_info'):
                ImageInfo.objects.create(image=local_image)
                local_image.refresh_from_db()

            hash_ = local_image.image_info.image_hash

            if hash_ in self.image_hashes:
                self.log(WARNING, "Image found with matching hash", context={
                    "composite hash": hash_,
                    "hashed image ID": self.image_hashes[hash_].id,
                    "matching image ID": local_image.id,
                })
            else:
                self.image_hashes[hash_] = local_image

            self.log(ACTION, "{}/{} images processed".format(count, total))
            count += 1