Write the TIFF file to the image bytes
506892
public void writeTiff() {
		if (directory.getWriteRasters() != null) {
			TIFFImage tiffImage = new TIFFImage();
			tiffImage.add(directory);
			try {
				imageBytes = TiffWriter.writeTiffToBytes(tiffImage);
			} catch (IOException e) {
				throw new GeoPackageException("Failed to write TIFF image", e);
			}
		}
	}
836439
private function bytes_to_file($bytes, $output_file) {
        $ifp = fopen($output_file, "wb");
        fwrite($ifp, $bytes);
        fclose($ifp);
    }
50663
public static void mergeTiff(File[] inputImages, File outputTiff) throws IOException {
        if (inputImages.length == 0) {
            // if no image
            return;
        }

        Iterator<ImageWriter> writers = ImageIO.getImageWritersByFormatName(TIFF_FORMAT);
        if (!writers.hasNext()) {
            throw new RuntimeException(JAI_IMAGE_WRITER_MESSAGE);
        }
        ImageWriter writer = writers.next();

        //Set up the writeParam
        TIFFImageWriteParam tiffWriteParam = new TIFFImageWriteParam(Locale.US);
//        tiffWriteParam.setCompressionMode(ImageWriteParam.MODE_DISABLED); // commented out to preserve original sizes

        //Get the stream metadata
        IIOMetadata streamMetadata = writer.getDefaultStreamMetadata(tiffWriteParam);

        try (ImageOutputStream ios = ImageIO.createImageOutputStream(outputTiff)) {
            writer.setOutput(ios);
            boolean firstPage = true;
            int index = 1;
            for (File inputImage : inputImages) {
                String imageFileFormat = getImageFileFormat(inputImage);
                Iterator<ImageReader> readers = ImageIO.getImageReadersByFormatName(imageFileFormat);
                if (!readers.hasNext()) {
                    throw new RuntimeException(JAI_IMAGE_READER_MESSAGE);
                }
                ImageReader reader = readers.next();
                try (ImageInputStream iis = ImageIO.createImageInputStream(inputImage)) {
                    reader.setInput(iis);
                    int imageTotal = reader.getNumImages(true);
                    for (int i = 0; i < imageTotal; i++) {
                        IIOImage oimage = reader.readAll(i, reader.getDefaultReadParam());
                        if (firstPage) {
                            writer.write(streamMetadata, oimage, tiffWriteParam);
                            firstPage = false;
                        } else {
                            writer.writeInsert(index++, oimage, tiffWriteParam);
                        }
                    }
                } finally {
                    if (reader != null) {
                        reader.dispose();
                    }
                }
            }
        } finally {
            writer.dispose();
        }
    }
389799
def write_bytes(fp, data):
    
    pos = fp.tell()
    fp.write(data)
    written = fp.tell() - pos
    assert written == len(data), 'written=%d, expected=%d' % (
        written, len(data)
    )
    return written
56356
def topng(images, path, prefix="image", overwrite=False, credentials=None):
    
    value_shape = images.value_shape
    if not len(value_shape) in [2, 3]:
        raise ValueError("Only 2D or 3D images can be exported to png, "
                         "images are %d-dimensional." % len(value_shape))

    from scipy.misc import imsave
    from io import BytesIO
    from thunder.writers import get_parallel_writer

    def tobuffer(kv):
        key, img = kv
        fname = prefix+"-"+"%05d.png" % int(key)
        bytebuf = BytesIO()
        imsave(bytebuf, img, format='PNG')
        return fname, bytebuf.getvalue()

    writer = get_parallel_writer(path)(path, overwrite=overwrite, credentials=credentials)
    images.foreach(lambda x: writer.write(tobuffer(x)))
141343
def write(self)->None:
        ""
        orig_images, gen_images, real_images = self._get_image_tensors()
        self._write_images(name='orig images', images=orig_images)
        self._write_images(name='gen images',  images=gen_images)
        self._write_images(name='real images', images=real_images)
536053
def write_idat(self, outfile, idat_sequence):
        
        # http://www.w3.org/TR/PNG/#5PNG-file-signature
        outfile.write(png_signature)
        color_type = 4 * self.alpha + 2 * (not self.greyscale) +\
            bool(self.palette)

        # http://www.w3.org/TR/PNG/#11IHDR
        write_chunk(outfile, 'IHDR',
                    struct.pack("!2I5B", self.width, self.height,
                                self.bitdepth, color_type,
                                0, 0, self.interlace))
        # See :chunk:order
        self.__write_srgb(outfile)
        # See :chunk:order
        # http://www.w3.org/TR/PNG/#11sBIT
        if not self.palette and self.pixbitdepth != self.bitdepth:
            # Write sBIT of palette within __write_palette
            # TODO: support different bitdepth per plane
            write_chunk(outfile, 'sBIT',
                        struct.pack('%dB' % self.planes,
                                    *[self.pixbitdepth] * self.planes))
        # :chunk:order: Without a palette (PLTE chunk), ordering is
        # relatively relaxed.  With one, gamma info must precede PLTE
        # chunk which must precede tRNS and bKGD.
        # See http://www.w3.org/TR/PNG/#5ChunkOrdering
        if self.palette:
            self.__write_palette(outfile)

        # http://www.w3.org/TR/PNG/#11tRNS
        if self.transparent is not None:
            if self.greyscale:
                write_chunk(outfile, 'tRNS',
                            struct.pack("!1H", *self.transparent))
            else:
                write_chunk(outfile, 'tRNS',
                            struct.pack("!3H", *self.transparent))

        # http://www.w3.org/TR/PNG/#11bKGD
        if self.background is not None:
            if self.greyscale:
                write_chunk(outfile, 'bKGD',
                            struct.pack("!1H", *self.background))
            else:
                write_chunk(outfile, 'bKGD',
                            struct.pack("!3H", *self.background))
        # http://www.w3.org/TR/PNG/#11pHYs
        if self.resolution is not None:
            write_chunk(outfile, 'pHYs',
                        struct.pack("!IIB",
                                    self.resolution[0][0],
                                    self.resolution[0][1],
                                    self.resolution[1]))
        # http://www.w3.org/TR/PNG/#11tIME
        if self.modification_time is not None:
            if self.modification_time is True:
                self.modification_time = check_time('now')
            write_chunk(outfile, 'tIME',
                        struct.pack("!H5B", *(self.modification_time[:6])))
        # http://www.w3.org/TR/PNG/#11textinfo
        if self.text:
            self.__write_text(outfile)
        for idat in idat_sequence:
            write_chunk(outfile, 'IDAT', idat)
        # http://www.w3.org/TR/PNG/#11IEND
        write_chunk(outfile, 'IEND')
1337969
def _pack_image(filename, max_size, form_field='image', f=None):
        """"""
        # image must be less than 700kb in size
        if f is None:
            try:
                if os.path.getsize(filename) > (max_size * 1024):
                    raise TweepError('File is too big, must be less than %skb.' % max_size)
            except os.error as e:
                raise TweepError('Unable to access file: %s' % e.strerror)

            # build the mulitpart-formdata body
            fp = open(filename, 'rb')
        else:
            f.seek(0, 2)  # Seek to end of file
            if f.tell() > (max_size * 1024):
                raise TweepError('File is too big, must be less than %skb.' % max_size)
            f.seek(0)  # Reset to beginning of file
            fp = f

        # image must be gif, jpeg, or png
        file_type = mimetypes.guess_type(filename)
        if file_type is None:
            raise TweepError('Could not determine file type')
        file_type = file_type[0]
        if file_type not in ['image/gif', 'image/jpeg', 'image/png']:
            raise TweepError('Invalid file type for image: %s' % file_type)

        if isinstance(filename, six.text_type):
            filename = filename.encode('utf-8')

        BOUNDARY = b'Tw3ePy'
        body = []
        body.append(b'--' + BOUNDARY)
        body.append('Content-Disposition: form-data; name="{0}";'
                    ' filename="{1}"'.format(form_field, filename)
                    .encode('utf-8'))
        body.append('Content-Type: {0}'.format(file_type).encode('utf-8'))
        body.append(b'')
        body.append(fp.read())
        body.append(b'--' + BOUNDARY + b'--')
        body.append(b'')
        fp.close()
        body = b'\r\n'.join(body)

        # build headers
        headers = {
            'Content-Type': 'multipart/form-data; boundary=Tw3ePy',
            'Content-Length': str(len(body))
        }

        return headers, body
1072628
def WriteBlobToFile(self, request):
    """"""
    # First chunk truncates the file, later chunks append.
    if request.offset == 0:
      mode = "w+b"
    else:
      mode = "r+b"

    temp_file = tempfiles.CreateGRRTempFile(
        filename=request.write_path, mode=mode)
    with temp_file:
      path = temp_file.name
      temp_file.seek(0, 2)
      if temp_file.tell() != request.offset:
        raise IOError("Chunks out of order Error.")

      # Write the new chunk.
      temp_file.write(request.executable.data)

    return path
648466
protected void writeFull() {
        byte[] imageData = rawImage.getData();
        int numOfComponents = frameHeader.getNf();
        int[] pixes = new int[numOfComponents * DCTSIZE2];
        int blockIndex = 0;
        int startCoordinate = 0, scanlineStride = numOfComponents * rawImage.getWidth(), row = 0;

        x = 0;
        y = 0;

        for (int m = 0; m < MCUsPerColumn * MCUsPerRow; m++) {
            blockIndex = 0;

            // one MCU
            for (int v = 0; v < maxVSampleFactor; v++) {
                for (int h = 0; h < maxHSampleFactor; h++) {
                    row = y + 1;
                    startCoordinate = (y * rawImage.getWidth() + x) * numOfComponents;

                    // one block
                    for (int k = blockIndex * DCTSIZE2, i = 0; k < blockIndex * DCTSIZE2 + DCTSIZE2; k++) {
                        pixes[i++] = allMCUDatas[0][m][k];

                        if (numOfComponents > 1) {
                            pixes[i++] = allMCUDatas[1][m][k];
                            pixes[i++] = allMCUDatas[2][m][k];
                        }

                        if (numOfComponents > 3) {
                            pixes[i++] = allMCUDatas[3][m][k];
                        }

                        x++;

                        if (x % 8 == 0) {
                            y++;
                            x -= 8;
                        }
                    }

                    colorConvertor.convertBlock(pixes, 0, imageData, numOfComponents, startCoordinate, row,
                                                scanlineStride);

                    blockIndex++;

                    x += 8;
                    y -= 8;
                }

                x -= maxHSampleFactor * 8;
                y += 8;
            }

            x += maxHSampleFactor * 8;
            y -= maxVSampleFactor * 8;

            if (x >= rawImage.getWidth()) {
                x = 0;
                y += maxVSampleFactor * 8;
            }

        }
    }
606840
def write_outxy(self,filename):
        
        f = open(filename,'w')
        f.write("#Pixel positions for: "+self.name+'\n')
        f.write("#X           Y\n")
        f.write("#(pix)       (pix)\n")
        for i in range(self.all_radec[0].shape[0]):
            f.write('%f  %f\n'%(self.outxy[i,0],self.outxy[i,1]))
        f.close()
897338
def writeMNIST(sc, input_images, input_labels, output, format, num_partitions):
  """"""
  # load MNIST gzip into memory
  with open(input_images, 'rb') as f:
    images = numpy.array(mnist.extract_images(f))

  with open(input_labels, 'rb') as f:
    if format == "csv2":
      labels = numpy.array(mnist.extract_labels(f, one_hot=False))
    else:
      labels = numpy.array(mnist.extract_labels(f, one_hot=True))

  shape = images.shape
  print("images.shape: {0}".format(shape))          # 60000 x 28 x 28
  print("labels.shape: {0}".format(labels.shape))   # 60000 x 10

  # create RDDs of vectors
  imageRDD = sc.parallelize(images.reshape(shape[0], shape[1] * shape[2]), num_partitions)
  labelRDD = sc.parallelize(labels, num_partitions)

  output_images = output + "/images"
  output_labels = output + "/labels"

  # save RDDs as specific format
  if format == "pickle":
    imageRDD.saveAsPickleFile(output_images)
    labelRDD.saveAsPickleFile(output_labels)
  elif format == "csv":
    imageRDD.map(toCSV).saveAsTextFile(output_images)
    labelRDD.map(toCSV).saveAsTextFile(output_labels)
  elif format == "csv2":
    imageRDD.map(toCSV).zip(labelRDD).map(lambda x: str(x[1]) + "|" + x[0]).saveAsTextFile(output)
  else:  # format == "tfr":
    tfRDD = imageRDD.zip(labelRDD).map(lambda x: (bytearray(toTFExample(x[0], x[1])), None))
    # requires: --jars tensorflow-hadoop-1.0-SNAPSHOT.jar
    tfRDD.saveAsNewAPIHadoopFile(output, "org.tensorflow.hadoop.io.TFRecordFileOutputFormat",
                                 keyClass="org.apache.hadoop.io.BytesWritable",
                                 valueClass="org.apache.hadoop.io.NullWritable")
1153517
def image_encode(args, i, item, q_out):
    
    fullpath = os.path.join(args.root, item[1])

    if len(item) > 3 and args.pack_label:
        header = mx.recordio.IRHeader(0, item[2:], item[0], 0)
    else:
        header = mx.recordio.IRHeader(0, item[2], item[0], 0)

    if args.pass_through:
        try:
            with open(fullpath, 'rb') as fin:
                img = fin.read()
            s = mx.recordio.pack(header, img)
            q_out.put((i, s, item))
        except Exception as e:
            traceback.print_exc()
            print('pack_img error:', item[1], e)
            q_out.put((i, None, item))
        return

    try:
        img = cv2.imread(fullpath, args.color)
    except:
        traceback.print_exc()
        print('imread error trying to load file: %s ' % fullpath)
        q_out.put((i, None, item))
        return
    if img is None:
        print('imread read blank (None) image for file: %s' % fullpath)
        q_out.put((i, None, item))
        return
    if args.center_crop:
        if img.shape[0] > img.shape[1]:
            margin = (img.shape[0] - img.shape[1]) // 2
            img = img[margin:margin + img.shape[1], :]
        else:
            margin = (img.shape[1] - img.shape[0]) // 2
            img = img[:, margin:margin + img.shape[0]]
    if args.resize:
        if img.shape[0] > img.shape[1]:
            newsize = (args.resize, img.shape[0] * args.resize // img.shape[1])
        else:
            newsize = (img.shape[1] * args.resize // img.shape[0], args.resize)
        img = cv2.resize(img, newsize)

    try:
        s = mx.recordio.pack_img(header, img, quality=args.quality, img_fmt=args.encoding)
        q_out.put((i, s, item))
    except Exception as e:
        traceback.print_exc()
        print('pack_img error on file: %s' % fullpath, e)
        q_out.put((i, None, item))
        return
218439
def _write_bytes(stream: Union[StdSim, TextIO], to_write: bytes) -> None:
        
        try:
            stream.buffer.write(to_write)
        except BrokenPipeError:
            # This occurs if output is being piped to a process that closed
            pass
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)}')
369396
public static void mergeTiff(List<IIOImage> imageList, File outputTiff, String compressionType) throws IOException {
        if (imageList == null || imageList.isEmpty()) {
            // if no image
            return;
        }

        Iterator<ImageWriter> writers = ImageIO.getImageWritersByFormatName(TIFF_FORMAT);
        if (!writers.hasNext()) {
            throw new RuntimeException(JAI_IMAGE_WRITER_MESSAGE);
        }
        ImageWriter writer = writers.next();

        //Set up the writeParam
        TIFFImageWriteParam tiffWriteParam = new TIFFImageWriteParam(Locale.US);
//        tiffWriteParam.setCompressionMode(ImageWriteParam.MODE_DISABLED); // comment out to preserve original sizes
        if (compressionType != null) {
            tiffWriteParam.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
            tiffWriteParam.setCompressionType(compressionType);
        }

        //Get the stream metadata
        IIOMetadata streamMetadata = writer.getDefaultStreamMetadata(tiffWriteParam);

        try (ImageOutputStream ios = ImageIO.createImageOutputStream(outputTiff)) {
            writer.setOutput(ios);

            int dpiX = 300;
            int dpiY = 300;

            for (IIOImage iioImage : imageList) {
                // Get the default image metadata.
                ImageTypeSpecifier imageType = ImageTypeSpecifier.createFromRenderedImage(iioImage.getRenderedImage());
                ImageWriteParam param = writer.getDefaultWriteParam();
                IIOMetadata imageMetadata = writer.getDefaultImageMetadata(imageType, param);
                imageMetadata = setDPIViaAPI(imageMetadata, dpiX, dpiY);
                iioImage.setMetadata(imageMetadata);
            }

            IIOImage firstIioImage = imageList.remove(0);
            writer.write(streamMetadata, firstIioImage, tiffWriteParam);

            int i = 1;
            for (IIOImage iioImage : imageList) {
                writer.writeInsert(i++, iioImage, tiffWriteParam);
            }
        } finally {
            writer.dispose();
        }
    }
227268
def save(self, fn:PathOrStr):
        ""
        x = image2np(self.data*255).astype(np.uint8)
        PIL.Image.fromarray(x).save(fn)