Take a python object and convert it to the format Imgur expects.
327180
def convert_general(value):
    """"""
    if isinstance(value, bool):
        return "true" if value else "false"
    elif isinstance(value, list):
        value = [convert_general(item) for item in value]
        value = convert_to_imgur_list(value)
    elif isinstance(value, Integral):
        return str(value)
    elif 'pyimgur' in str(type(value)):
        return str(getattr(value, 'id', value))
    return value
121783
def to_pillow_image(self, return_mask=False):
        """"""
        img = np.rollaxis(np.rollaxis(self.image.data, 2), 2)
        img = Image.fromarray(img[:, :, 0]) if img.shape[2] == 1 else Image.fromarray(img)
        if return_mask:
            mask = np.ma.getmaskarray(self.image)
            mask = Image.fromarray(np.rollaxis(np.rollaxis(mask, 2), 2).astype(np.uint8)[:, :, 0])
            return img, mask
        else:
            return img
442365
def convert_image(from_file, to_file, image_format):
    """"""
    with Image(filename=from_file) as original:
        with original.convert(image_format) as converted:
            converted.save(filename=to_file)
    return to_file
96516
def to_image(self, digest, blob, mime_type, index, size=500):
        
        # Special case, for now (XXX).
        if mime_type.startswith("image/"):
            return ""

        cache_key = f"img:{index}:{size}:{digest}"
        converted = self.cache.get(cache_key)
        if converted:
            return converted

        # Direct conversion possible
        for handler in self.handlers:
            if handler.accept(mime_type, "image/jpeg"):
                converted_images = handler.convert(blob, size=size)
                for i in range(0, len(converted_images)):
                    converted = converted_images[i]
                    cache_key = f"img:{i}:{size}:{digest}"
                    self.cache[cache_key] = converted
                return converted_images[index]

        # Use PDF as a pivot format
        pdf = self.to_pdf(digest, blob, mime_type)
        for handler in self.handlers:
            if handler.accept("application/pdf", "image/jpeg"):
                converted_images = handler.convert(pdf, size=size)
                for i in range(0, len(converted_images)):
                    converted = converted_images[i]
                    cache_key = f"img:{i}:{size}:{digest}"
                    self.cache[cache_key] = converted
                return converted_images[index]

        raise HandlerNotFound(f"No handler found to convert from {mime_type} to image")
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
455869
def gen_image(img, width, height, outfile, img_type='grey'):
    """"""
    assert len(img) == width * height or len(img) == width * height * 3

    if img_type == 'grey':
        misc.imsave(outfile, img.reshape(width, height))

    elif img_type == 'color':
        misc.imsave(outfile, img.reshape(3, width, height))
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
649061
def getImageObject(url, referrer, session, max_content_bytes=MaxImageBytes):
    """"""
    return urlopen(url, session, referrer=referrer, max_content_bytes=max_content_bytes, stream=True)
284938
def pretty_format(obj, indent=None):
        
        if indent is None:
            if isinstance(obj, TLObject):
                obj = obj.to_dict()

            if isinstance(obj, dict):
                return '{}({})'.format(obj.get('_', 'dict'), ', '.join(
                    '{}={}'.format(k, TLObject.pretty_format(v))
                    for k, v in obj.items() if k != '_'
                ))
            elif isinstance(obj, str) or isinstance(obj, bytes):
                return repr(obj)
            elif hasattr(obj, '__iter__'):
                return '[{}]'.format(
                    ', '.join(TLObject.pretty_format(x) for x in obj)
                )
            else:
                return repr(obj)
        else:
            result = []
            if isinstance(obj, TLObject):
                obj = obj.to_dict()

            if isinstance(obj, dict):
                result.append(obj.get('_', 'dict'))
                result.append('(')
                if obj:
                    result.append('\n')
                    indent += 1
                    for k, v in obj.items():
                        if k == '_':
                            continue
                        result.append('\t' * indent)
                        result.append(k)
                        result.append('=')
                        result.append(TLObject.pretty_format(v, indent))
                        result.append(',\n')
                    result.pop()  # last ',\n'
                    indent -= 1
                    result.append('\n')
                    result.append('\t' * indent)
                result.append(')')

            elif isinstance(obj, str) or isinstance(obj, bytes):
                result.append(repr(obj))

            elif hasattr(obj, '__iter__'):
                result.append('[\n')
                indent += 1
                for x in obj:
                    result.append('\t' * indent)
                    result.append(TLObject.pretty_format(x, indent))
                    result.append(',\n')
                indent -= 1
                result.append('\t' * indent)
                result.append(']')

            else:
                result.append(repr(obj))

            return ''.join(result)
1337025
def png(self):
        """"""
        use_plugin('freeimage')
        with TemporaryFilePath(suffix='.png') as tmp:
            safe_range_im = 255 * normalise(self)
            imsave(tmp.fpath, safe_range_im.astype(np.uint8))
            with open(tmp.fpath, 'rb') as fh:
                return fh.read()
267329
def format_image(self, image, image_format, **kwargs):
        """"""

        image_format = image_format.lower()
        accept = self.request.META['HTTP_ACCEPT'].split(',')

        if FORCE_WEBP and 'image/webp' in accept:
            image_format = 'webp'
        elif image_format == 'png8':
            alpha = image.split()[-1]
            image = image.convert('RGB')
            image = image.convert('P', palette=Image.ADAPTIVE, colors=255)
            image.paste(255, Image.eval(alpha, lambda x: 255 if x <= 128 else 0))
            image_format = 'png'
            kwargs['transparency'] = 255
        elif image_format in ('png32', 'png24'):
            image_format = 'png'

        return super(GetImageView, self).format_image(image, image_format, **kwargs)
1233351
def _main():
    
    import pprint
    import tempfile

    try:
        image = sys.argv[1]
    except IndexError:
        print("Usage: python -m pyrobase.webservice.imgur <url>")
    else:
        try:
            pprint.pprint(copy_image_from_url(image, cache_dir=tempfile.gettempdir()))
        except UploadError as exc:
            print("Upload error. %s" % exc)
1183319
def imread(img, color=None, dtype=None):
    '''
    
    '''
    COLOR2CV = {'gray': cv2.IMREAD_GRAYSCALE,
                'all': cv2.IMREAD_COLOR,
                None: cv2.IMREAD_ANYCOLOR
                }
    c = COLOR2CV[color]
    if callable(img):
        img = img()
    elif isinstance(img, string_types):
        #         from_file = True
        #         try:
        #             ftype = img[img.find('.'):]
        #             img = READERS[ftype](img)[0]
        #         except KeyError:
        # open with openCV
        # grey - 8 bit
        if dtype in (None, "noUint") or np.dtype(dtype) != np.uint8:
            c |= cv2.IMREAD_ANYDEPTH
        img2 = cv2.imread(img, c)
        if img2 is None:
            raise IOError("image '%s' is not existing" % img)
        img = img2

    elif color == 'gray' and img.ndim == 3:  # multi channel img like rgb
        # cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) #cannot handle float64
        img = toGray(img)
    # transform array to uint8 array due to openCV restriction
    if dtype is not None:
        if isinstance(img, np.ndarray):
            img = _changeArrayDType(img, dtype, cutHigh=False)

    return img
559017
def as_PIL(self):
        
        if isinstance(self.data, numpy.ndarray):
            if self.data.dtype == numpy.uint8:
                result = PIL.Image.fromarray(self.data)
            else:
                result = PIL.Image.fromarray(
                    self.data.clip(0, 255).astype(numpy.uint8))
        elif isinstance(self.data, PIL.Image.Image):
            result = self.data
        else:
            raise RuntimeError(
                'Cannot convert "%s" to PIL' % self.data.__class__.__name__)
        return result
678319
def as_pil_image(self):
        
        from PIL import Image

        try:
            bio = BytesIO()
            self._extract_direct(stream=bio)
            bio.seek(0)
            return Image.open(bio)
        except UnsupportedImageTypeError:
            pass

        im = self._extract_transcoded()
        if not im:
            raise UnsupportedImageTypeError(repr(self))

        return im
641566
def get_image(self, cat, img):
        
        filename = self.path(cat, img)
        data = []
        if filename.endswith('mat'):
            data = loadmat(filename)['output']
        else:
            data = imread(filename)
        if self.size is not None:
            return imresize(data, self.size)
        else:
            return data
787211
def convert(f, opts = {})
      opts = opts.dup
      f = f.to_s.downcase
      allowed = %w(jpeg jpg png)
      raise ArgumentError, "Format must be one of: #{allowed.join(',')}" unless allowed.include?(f)
      self.format_override = f == 'jpeg' ? 'jpg' : f
      opts[:Q] = opts.delete(:quality) if opts.has_key?(:quality)
      write_opts.merge!(opts)
      get_image
    end