图像切割(按指定起点坐标和宽高切割)

@param srcImgFile 源图像文件
@param destImgFile 切片后的图像文件
@param rectangle 矩形对象，表示矩形区域的x，y，width，height
@since 3.1.0
772953
public static void cut(File srcImgFile, File destImgFile, Rectangle rectangle) {
		cut(read(srcImgFile), destImgFile, rectangle);
	}
969660
void dus(String src) throws IOException {
    Path srcPath = new Path(src);
    FileSystem srcFs = srcPath.getFileSystem(getConf());
    FileStatus status[] = srcFs.globStatus(new Path(src));
    if (status==null || status.length==0) {
      throw new FileNotFoundException("Cannot access " + src + 
          ": No such file or directory.");
    }
    for(int i=0; i<status.length; i++) {
      long totalSize = srcFs.getContentSummary(status[i].getPath()).getLength();
      String pathStr = status[i].getPath().toString();
      System.out.println(("".equals(pathStr)?".":pathStr) + "\t" + totalSize);
    }
  }
1290748
public void copy(
      JimfsPath source,
      FileSystemView destView,
      JimfsPath dest,
      Set<CopyOption> options,
      boolean move)
      throws IOException {
    checkNotNull(source);
    checkNotNull(destView);
    checkNotNull(dest);
    checkNotNull(options);

    boolean sameFileSystem = isSameFileSystem(destView);

    File sourceFile;
    File copyFile = null; // non-null after block completes iff source file was copied
    lockBoth(store.writeLock(), destView.store.writeLock());
    try {
      DirectoryEntry sourceEntry = lookUp(source, options).requireExists(source);
      DirectoryEntry destEntry = destView.lookUp(dest, Options.NOFOLLOW_LINKS);

      Directory sourceParent = sourceEntry.directory();
      sourceFile = sourceEntry.file();

      Directory destParent = destEntry.directory();

      if (move && sourceFile.isDirectory()) {
        if (sameFileSystem) {
          checkMovable(sourceFile, source);
          checkNotAncestor(sourceFile, destParent, destView);
        } else {
          // move to another file system is accomplished by copy-then-delete, so the source file
          // must be deletable to be moved
          checkDeletable(sourceFile, DeleteMode.ANY, source);
        }
      }

      if (destEntry.exists()) {
        if (destEntry.file().equals(sourceFile)) {
          return;
        } else if (options.contains(REPLACE_EXISTING)) {
          destView.delete(destEntry, DeleteMode.ANY, dest);
        } else {
          throw new FileAlreadyExistsException(dest.toString());
        }
      }

      if (move && sameFileSystem) {
        // Real move on the same file system.
        sourceParent.unlink(source.name());
        sourceParent.updateModifiedTime();

        destParent.link(dest.name(), sourceFile);
        destParent.updateModifiedTime();
      } else {
        // Doing a copy OR a move to a different file system, which must be implemented by copy and
        // delete.

        // By default, don't copy attributes.
        AttributeCopyOption attributeCopyOption = AttributeCopyOption.NONE;
        if (move) {
          // Copy only the basic attributes of the file to the other file system, as it may not
          // support all the attribute views that this file system does. This also matches the
          // behavior of moving a file to a foreign file system with a different
          // FileSystemProvider.
          attributeCopyOption = AttributeCopyOption.BASIC;
        } else if (options.contains(COPY_ATTRIBUTES)) {
          // As with move, if we're copying the file to a different file system, only copy its
          // basic attributes.
          attributeCopyOption =
              sameFileSystem ? AttributeCopyOption.ALL : AttributeCopyOption.BASIC;
        }

        // Copy the file, but don't copy its content while we're holding the file store locks.
        copyFile = destView.store.copyWithoutContent(sourceFile, attributeCopyOption);
        destParent.link(dest.name(), copyFile);
        destParent.updateModifiedTime();

        // In order for the copy to be atomic (not strictly necessary, but seems preferable since
        // we can) lock both source and copy files before leaving the file store locks. This
        // ensures that users cannot observe the copy's content until the content has been copied.
        // This also marks the source file as opened, preventing its content from being deleted
        // until after it's copied if the source file itself is deleted in the next step.
        lockSourceAndCopy(sourceFile, copyFile);

        if (move) {
          // It should not be possible for delete to throw an exception here, because we already
          // checked that the file was deletable above.
          delete(sourceEntry, DeleteMode.ANY, source);
        }
      }
    } finally {
      destView.store.writeLock().unlock();
      store.writeLock().unlock();
    }

    if (copyFile != null) {
      // Copy the content. This is done outside the above block to minimize the time spent holding
      // file store locks, since copying the content of a regular file could take a (relatively)
      // long time. If done inside the above block, copying using Files.copy can be slower than
      // copying with an InputStream and an OutputStream if many files are being copied on
      // different threads.
      try {
        sourceFile.copyContentTo(copyFile);
      } finally {
        // Unlock the files, allowing the content of the copy to be observed by the user. This also
        // closes the source file, allowing its content to be deleted if it was deleted.
        unlockSourceAndCopy(sourceFile, copyFile);
      }
    }
  }
336850
public void toWEBP(String src, String dest) {
        toWEBP(new File(src), new File(dest));
    }
1266139
@Pure
	public static URL generateShapeFileIndexFromShapeFile(File shapeFile) throws IOException {
		final File shxFile = FileSystem.replaceExtension(shapeFile, "." + ShapeFileIndexFilter.EXTENSION_SHX); //$NON-NLS-1$

		try (ShapeFileReader<Object> shpReader = new ShapeFileReader<>(shapeFile, new NullFactory())) {

			try (ShapeFileIndexWriter shxWriter = new ShapeFileIndexWriter(
					shxFile,
					shpReader.getShapeElementType(),
					shpReader.getBoundsFromHeader())) {
				int offset = shpReader.getFileReadingPosition();
				int newOffset;
				int shpLength;

				while (shpReader.read() != null) {
					newOffset = shpReader.getFileReadingPosition();
					// byte length - file header length - record header length
					shpLength = newOffset - offset;
					shxWriter.write(shpLength);
					offset = newOffset;
				}
			}
		}

		return shxFile.toURI().toURL();
	}
944387
@Override
  public void initializeFromFile(TreeIndexHeader header, PageFile<N> file) {
    super.initializeFromFile(header, file);
    // compute height
    this.height = computeHeight();

    if(getLogger().isDebugging()) {
      getLogger().debugFine(new StringBuilder(100).append(getClass()) //
          .append("\n height = ").append(height).toString());
    }
  }
1214993
public static void renameFile(File srcFile, File dstFile) throws IOException
   {
      // Rename the srcFile file to the new one. Unfortunately, the renameTo()
      // method does not work reliably under some JVMs.  Therefore, if the
      // rename fails, we manually rename by copying the srcFile file to the new one
      if (!srcFile.renameTo(dstFile))
      {
         InputStream in = null;
         OutputStream out = null;
         try
         {
            in = new FileInputStream(srcFile);
            out = new FileOutputStream(dstFile);

            transfer(in, out);
         }
         catch (IOException ioe)
         {
            IOException newExc = new IOException("Cannot rename " + srcFile + " to " + dstFile);
            newExc.initCause(ioe);
            throw newExc;
         }
         finally
         {
            if (in != null)
            {
               in.close();
            }

            if (out != null)
            {
               out.close();
            }
         }

         // delete the srcFile file.
         srcFile.delete();
      }
   }
1331496
private void setLastBlockSize(INodeFileUnderConstruction pendingFile) {
    Block block = pendingFile.getLastBlock();
    if (block != null) {
      block.setNumBytes(pendingFile.getPreferredBlockSize());
    }
  }
334664
public final void compress(ByteBuffer src, ByteBuffer dest) {
    final int cpLen = compress(src, src.position(), src.remaining(), dest, dest.position(), dest.remaining());
    src.position(src.limit());
    dest.position(dest.position() + cpLen);
  }
1235030
public static void readSourceFileAndWriteDestFile(final String srcfile, final String destFile)
		throws IOException
	{
		try (FileInputStream fis = new FileInputStream(srcfile);
			FileOutputStream fos = new FileOutputStream(destFile);
			BufferedInputStream bis = new BufferedInputStream(fis);
			BufferedOutputStream bos = new BufferedOutputStream(fos);)
		{
			final int availableLength = bis.available();
			final byte[] totalBytes = new byte[availableLength];
			bis.read(totalBytes, 0, availableLength);
			bos.write(totalBytes, 0, availableLength);
		}
	}
564012
public static final boolean intersection(Rectangle src1, Rectangle src2, Rectangle dest)
    {
        int x1 = Math.max(src1.x, src2.x);
        int y1 = Math.max(src1.y, src2.y);
        int x2 = Math.min(src1.x + src1.width, src2.x + src2.width);
        int y2 = Math.min(src1.y + src1.height, src2.y + src2.height);
        dest.setBounds(x1, y1, x2 - x1, y2 - y1);

        if (dest.width <= 0 || dest.height <= 0)
            return false;

        return true; // non-empty intersection
    }
1356825
public static void slice(File srcImageFile, File descDir, int destWidth, int destHeight) {
		slice(read(srcImageFile), descDir, destWidth, destHeight);
	}
624615
public static void cut(Image srcImage, ImageOutputStream destImageStream, Rectangle rectangle) throws IORuntimeException {
		writeJpg(cut(srcImage, rectangle), destImageStream);
	}
734665
function(width,height,depth) {

			this.width   = width;
			this.height  = height;
			this.depth   = depth;

			// pixel data and row filter identifier size
			this.pix_size = height * (width + 1);

			// deflate header, pix_size, block headers, adler32 checksum
			this.data_size = 2 + this.pix_size + 5 * Math.floor((0xfffe + this.pix_size) / 0xffff) + 4;

			// offsets and sizes of Png chunks
			this.ihdr_offs = 0;									// IHDR offset and size
			this.ihdr_size = 4 + 4 + 13 + 4;
			this.plte_offs = this.ihdr_offs + this.ihdr_size;	// PLTE offset and size
			this.plte_size = 4 + 4 + 3 * depth + 4;
			this.trns_offs = this.plte_offs + this.plte_size;	// tRNS offset and size
			this.trns_size = 4 + 4 + depth + 4;
			this.idat_offs = this.trns_offs + this.trns_size;	// IDAT offset and size
			this.idat_size = 4 + 4 + this.data_size + 4;
			this.iend_offs = this.idat_offs + this.idat_size;	// IEND offset and size
			this.iend_size = 4 + 4 + 4;
			this.buffer_size  = this.iend_offs + this.iend_size;	// total PNG size

			this.buffer  = new Array();
			this.palette = new Object();
			this.pindex  = 0;

			var _crc32 = new Array();

			// initialize buffer with zero bytes
			for (var i = 0; i < this.buffer_size; i++) {
				this.buffer[i] = "\x00";
			}

			// initialize non-zero elements
			write(this.buffer, this.ihdr_offs, byte4(this.ihdr_size - 12), 'IHDR', byte4(width), byte4(height), "\x08\x03");
			write(this.buffer, this.plte_offs, byte4(this.plte_size - 12), 'PLTE');
			write(this.buffer, this.trns_offs, byte4(this.trns_size - 12), 'tRNS');
			write(this.buffer, this.idat_offs, byte4(this.idat_size - 12), 'IDAT');
			write(this.buffer, this.iend_offs, byte4(this.iend_size - 12), 'IEND');

			// initialize deflate header
			var header = ((8 + (7 << 4)) << 8) | (3 << 6);
			header+= 31 - (header % 31);

			write(this.buffer, this.idat_offs + 8, byte2(header));

			// initialize deflate block headers
			for (var i = 0; (i << 16) - 1 < this.pix_size; i++) {
				var size, bits;
				if (i + 0xffff < this.pix_size) {
					size = 0xffff;
					bits = "\x00";
				} else {
					size = this.pix_size - (i << 16) - i;
					bits = "\x01";
				}
				write(this.buffer, this.idat_offs + 8 + 2 + (i << 16) + (i << 2), bits, byte2lsb(size), byte2lsb(~size));
			}

			/* Create crc32 lookup table */
			for (var i = 0; i < 256; i++) {
				var c = i;
				for (var j = 0; j < 8; j++) {
					if (c & 1) {
						c = -306674912 ^ ((c >> 1) & 0x7fffffff);
					} else {
						c = (c >> 1) & 0x7fffffff;
					}
				}
				_crc32[i] = c;
			}

			// compute the index into a png for a given pixel
			this.index = function(x,y) {
				var i = y * (this.width + 1) + x + 1;
				var j = this.idat_offs + 8 + 2 + 5 * Math.floor((i / 0xffff) + 1) + i;
				return j;
			};

			// convert a color and build up the palette
			this.color = function(red, green, blue, alpha) {

				alpha = alpha >= 0 ? alpha : 255;
				var color = (((((alpha << 8) | red) << 8) | green) << 8) | blue;

				if (typeof this.palette[color] == "undefined") {
					if (this.pindex == this.depth) return "\x00";

					var ndx = this.plte_offs + 8 + 3 * this.pindex;

					this.buffer[ndx + 0] = String.fromCharCode(red);
					this.buffer[ndx + 1] = String.fromCharCode(green);
					this.buffer[ndx + 2] = String.fromCharCode(blue);
					this.buffer[this.trns_offs+8+this.pindex] = String.fromCharCode(alpha);

					this.palette[color] = String.fromCharCode(this.pindex++);
				}
				return this.palette[color];
			};

			// output a PNG string, Base64 encoded
			this.getBase64 = function() {

				var s = this.getDump();

				var ch = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
				var c1, c2, c3, e1, e2, e3, e4;
				var l = s.length;
				var i = 0;
				var r = "";

				do {
					c1 = s.charCodeAt(i);
					e1 = c1 >> 2;
					c2 = s.charCodeAt(i+1);
					e2 = ((c1 & 3) << 4) | (c2 >> 4);
					c3 = s.charCodeAt(i+2);
					if (l < i+2) { e3 = 64; } else { e3 = ((c2 & 0xf) << 2) | (c3 >> 6); }
					if (l < i+3) { e4 = 64; } else { e4 = c3 & 0x3f; }
					r+= ch.charAt(e1) + ch.charAt(e2) + ch.charAt(e3) + ch.charAt(e4);
				} while ((i+= 3) < l);
				return r;
			};

			// output a PNG string
			this.getDump = function() {

				// compute adler32 of output pixels + row filter bytes
				var BASE = 65521; /* largest prime smaller than 65536 */
				var NMAX = 5552;  /* NMAX is the largest n such that 255n(n+1)/2 + (n+1)(BASE-1) <= 2^32-1 */
				var s1 = 1;
				var s2 = 0;
				var n = NMAX;

				for (var y = 0; y < this.height; y++) {
					for (var x = -1; x < this.width; x++) {
						s1+= this.buffer[this.index(x, y)].charCodeAt(0);
						s2+= s1;
						if ((n-= 1) == 0) {
							s1%= BASE;
							s2%= BASE;
							n = NMAX;
						}
					}
				}
				s1%= BASE;
				s2%= BASE;
				write(this.buffer, this.idat_offs + this.idat_size - 8, byte4((s2 << 16) | s1));

				// compute crc32 of the PNG chunks
				function crc32(png, offs, size) {
					var crc = -1;
					for (var i = 4; i < size-4; i += 1) {
						crc = _crc32[(crc ^ png[offs+i].charCodeAt(0)) & 0xff] ^ ((crc >> 8) & 0x00ffffff);
					}
					write(png, offs+size-4, byte4(crc ^ -1));
				}

				crc32(this.buffer, this.ihdr_offs, this.ihdr_size);
				crc32(this.buffer, this.plte_offs, this.plte_size);
				crc32(this.buffer, this.trns_offs, this.trns_size);
				crc32(this.buffer, this.idat_offs, this.idat_size);
				crc32(this.buffer, this.iend_offs, this.iend_size);

				// convert PNG to string
				return "\x89PNG\r\n\x1a\n"+this.buffer.join('');
			};
		}
598789
public void copyFile(final RelativeResource src, final RelativeResource dest)
		throws IOException {
		if (src.equals(dest)) {
			return;
		}
		LOG.debug("复制文件从 {} 到 {}", src, dest);
		File srcFile = getResource(src).getFile();
		if (!srcFile.exists()) {
			throw new FileNotFoundException(srcFile.getAbsolutePath());
		}
		File destFile = getResource(dest).getFile();
		deleteOldFile(destFile);
		FileUtils.copyFile(srcFile, destFile);
	}
756812
public static void copyFile(File srcFile, File destFile) throws IOException
    {
        InputStream reader = new FileInputStream(srcFile);
        OutputStream out = new FileOutputStream(destFile);
        try
        {
            byte[] buffer = new byte[2048];
            int n = 0;
            while (-1 != (n = reader.read(buffer))) 
            {
                out.write(buffer, 0, n);
            } 
        }
        finally
        {
            org.apache.commons.io.IOUtils.closeQuietly(out);
            org.apache.commons.io.IOUtils.closeQuietly(reader);
        }
    }
588307
public static void transferFileAtom(File src, File dest, boolean isDeleteSource) throws Exception {

        // 文件锁所在文件
        File lockFile = new File(dest + ".lock");
        FileOutputStream outStream = null;
        FileLock lock = null;

        try {
            outStream = new FileOutputStream(lockFile);
            FileChannel channel = outStream.getChannel();
            try {

                int tryTime = 0;
                while (tryTime < 3) {

                    lock = channel.tryLock();
                    if (lock != null) {

                        if (dest.exists()) {
                            // 判断内容是否一样
                            if (FileUtils.isFileEqual(src, dest)) {
                                // 删除
                                if (isDeleteSource) {
                                    src.delete();
                                }
                                break;
                            }
                        }

                        logger.debug("start to replace " + src.getAbsolutePath() + " to " + dest.getAbsolutePath());

                        // 转移
                        transferFile(src, dest);

                        // 删除
                        if (isDeleteSource) {
                            src.delete();
                        }

                        break;
                    }

                    logger.warn("try lock failed. sleep and try " + tryTime);
                    tryTime++;

                    try {
                        Thread.sleep(1000 * tryTime);
                    } catch (Exception e) {
                    }
                }

            } catch (IOException e) {
                logger.warn(e.toString());
            }

        } catch (FileNotFoundException e) {
            logger.warn(e.toString());

        } finally {

            if (null != lock) {
                try {
                    lock.release();
                } catch (IOException e) {
                    logger.warn(e.toString());
                }
            }
            if (outStream != null) {
                try {
                    outStream.close();
                } catch (IOException e) {
                    logger.warn(e.toString());
                }
            }
        }
    }