net.coobird.thumbnailator.Thumbnails Java Examples

The following examples show how to use net.coobird.thumbnailator.Thumbnails. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: UploadServiceImpl.java    From fileServer with Apache License 2.0 6 votes vote down vote up
private void uploadCutImages(List<ImageWH> whs,File sourceFile,StorePath path,String ext) throws ServiceException {
    //上传裁剪的图片
    try {
        for (ImageWH wh : whs) {

            ByteArrayOutputStream out = new ByteArrayOutputStream();
            Thumbnails.of(sourceFile).size(wh.getW(), wh.getH()).toOutputStream(out);
            InputStream newInput = new ByteArrayInputStream(out.toByteArray());

            int newSize = out.size();

            String prefixName = String.format("%dx%d", wh.getW(), wh.getH());

            StorePath slaveFile = storageClient.uploadSlaveFile(path.getGroup(), path.getPath(),
                    newInput, newSize, prefixName, ext);
            if (slaveFile == null) {
                throw new ServiceException("cutImage upload error.");
            }
        }
    }catch (Exception e){
        throw new ServiceException(e);
    }
}
 
Example #2
Source File: ImageUtils.java    From mySpringBoot with Apache License 2.0 6 votes vote down vote up
/**
 * 对原图加水印,然后顺时针旋转90度,最后压缩为80%保存
 */
public static void generateRotationWatermark(){
    try {
        Thumbnails.of("C:\\Users\\Administrator\\Desktop\\微信图片_20180129100019.jpg").
                // 缩放大小
                size(1600,1600).
                // 顺时针旋转90度
                rotate(90).
                //水印位于右下角,半透明
                watermark(Positions.BOTTOM_RIGHT, ImageIO.read(new File("C:\\Users\\Administrator\\Desktop\\微信图片_20180329153521.png")),1f).
                // 图片压缩80%质量
                outputQuality(0.8).
                toFile("C:\\Users\\Administrator\\Desktop\\2016010208_new.jpg");
    } catch (IOException e) {
        logger.error(e.getMessage());
    }
}
 
Example #3
Source File: ZipImageTest.java    From onetwo with Apache License 2.0 6 votes vote down vote up
@Test
public void testZip() throws Exception{
	String path = "F:/资料/云微科技/中大最美校园/pic/南校园素材1.rar";
	Thumbnails.fromFilenames(Arrays.asList(path))
				.scale(1)
				.outputQuality(0.01)
				.toFile("d:/test/zip2.jpg");;
}
 
Example #4
Source File: LocalFileHandler.java    From halo with GNU General Public License v3.0 6 votes vote down vote up
private boolean generateThumbnail(BufferedImage originalImage, Path thumbPath, String extension) {
    Assert.notNull(originalImage, "Image must not be null");
    Assert.notNull(thumbPath, "Thumb path must not be null");


    boolean result = false;
    // Create the thumbnail
    try {
        Files.createFile(thumbPath);
        // Convert to thumbnail and copy the thumbnail
        log.debug("Trying to generate thumbnail: [{}]", thumbPath.toString());
        Thumbnails.of(originalImage).size(THUMB_WIDTH, THUMB_HEIGHT).keepAspectRatio(true).toFile(thumbPath.toFile());
        log.debug("Generated thumbnail image, and wrote the thumbnail to [{}]", thumbPath.toString());
        result = true;
    } catch (Throwable t) {
        log.warn("Failed to generate thumbnail: " + thumbPath, t);
    } finally {
        // Disposes of this graphics context and releases any system resources that it is using.
        if (originalImage != null) {
            originalImage.getGraphics().dispose();
        }
    }
    return result;
}
 
Example #5
Source File: UploadController.java    From spring-admin-vue with Apache License 2.0 6 votes vote down vote up
/**
 * 图片压缩并且上传 七牛云 OSS
 *
 * @param file
 * @param height
 * @param width
 * @return Map<String, String>
 * @author Wang Chen Chen<[email protected]>
 * @date 2019/12/13 23:06
 */
private Map<String, String> uploadFile(MultipartFile file, int width, int height) throws IOException {
    // 获取一个空文件
    File targetFile = qiniuUtils.makeParentFolder(file.getOriginalFilename());
    // 因为是spring boot 打包以后是jar包,所以需要用ClassPathResource来获取classpath下面的水印图片
    InputStream watermark = new ClassPathResource("images/watermark.png").getInputStream();
    // 图片压缩以后读到空文件中
    Thumbnails.of(file.getInputStream())
            .watermark(Positions.BOTTOM_RIGHT, ImageIO.read(watermark), 0.5f)
            .outputQuality(0.8f)
            .size(width, height).toFile(targetFile);
    // 把压缩好的图片上传到 七牛云
    String url = qiniuUtils.upload(new FileInputStream(targetFile), targetFile.getName());
    Map<String, String> result = new HashMap<>(2);
    result.put("url", url);
    result.put("fileName", targetFile.getName());
    log.info("uploadFile( {} , {} , {} , {} );", file.getOriginalFilename(), file.getSize(), file.getContentType(), targetFile.getName(), url);
    // 删除压缩文件
    targetFile.delete();
    return result;
}
 
Example #6
Source File: Thumbnailator.java    From maven-framework-project with MIT License 6 votes vote down vote up
/**
 * 裁剪 
 */
@Test
public void example6() throws Exception{
	//sourceRegion()
	//图片中心400*400的区域
	Thumbnails.of("src/main/resources/example.jpg")
			.sourceRegion(Positions.CENTER, 400,400)
			.size(200, 200)
	        .keepAspectRatio(false) 
	        .toFile("src/main/resources/a380_region_center.jpg");

	//图片右下400*400的区域
	Thumbnails.of("src/main/resources/example.jpg")
			.sourceRegion(Positions.BOTTOM_RIGHT, 400,400)
			.size(200, 200)
	        .keepAspectRatio(false) 
	        .toFile("src/main/resources/a380_region_bootom_right.jpg");

	//指定坐标
	Thumbnails.of("src/main/resources/example.jpg")
			.sourceRegion(300, 250, 260, 260)
			.size(200, 200)
	        .keepAspectRatio(false) 
	        .toFile("src/main/resources/a380_region_coord.jpg");

}
 
Example #7
Source File: Thumb.java    From HongsCORE with MIT License 6 votes vote down vote up
/**
 * 按比例截取
 * 当 f 为 true 时强制缩放到 w*h, 为 false 仅按比例处理
 * @param w
 * @param h
 * @param f
 * @return
 */
public Builder pick(int w, int h, boolean f) {
    int tw , th;
    int sw = src.getWidth ();
    int sh = src.getHeight();
    int dw = sh * w / h; // 注意: 先乘再除能避免整形除法的精度损失
    if (dw > sw) {
        th = sw * h / w;
        tw = sw; // 宽度优先
    } else {
        tw = dw;
        th = sh; // 高度优先
    }

    BufferedImage img = draw(src, col, pos, tw, th, sw, sh);

    Builder bud = Thumbnails.of(img);
    if (f) {
        return  bud.forceSize  (w,h);
    } else {
        return  bud.scale(1);
    }
}
 
Example #8
Source File: ImageUtil.java    From Project with Apache License 2.0 6 votes vote down vote up
/**
 * 处理商品分类图
 *
 * @param thumbnail  Spring自带的文件处理对象
 * @param targetAddr 图片存储路径
 * @return
 */
public static String generateShopCategoryImg(ImageHolder thumbnail, String targetAddr) {
    // 获取随机文件名,防止文件重名
    String realFileName = getRandomFileName();
    // 获取文件扩展名
    String extension = getFileExtension(thumbnail.getImageName());
    // 在文件夹不存在时创建
    makeDirPath(targetAddr);
    String relativeAddr = targetAddr + realFileName + extension;
    File dest = new File(PathUtil.getImgBasePath() + relativeAddr);
    try {
        Thumbnails.of(thumbnail.getImage()).size(50, 50).outputQuality(0.9f).toFile(dest);
    } catch (IOException e) {
        throw new RuntimeException("创建缩略图失败:" + e.toString());
    }
    return relativeAddr;
}
 
Example #9
Source File: QRCodeUtils.java    From qrcodecore with GNU General Public License v2.0 6 votes vote down vote up
/**
 * 生成带有logo的二维码
 * @param text 生成文本
 * @param logoInputStream logo文件输入流
 * @param qrCodeWidth 二维码宽度
 * @param qrCodeHeight 二维码高度
 * @param logoWidth logo宽度
 * @param logoHeight logo高度
 * @param ENCODE_HINTS 二维码配置
 * @return 输出流
 * @throws WriterException
 * @throws IOException
 */
private static Thumbnails.Builder<BufferedImage> createWidthLogo(String text, InputStream logoInputStream, int qrCodeWidth, int qrCodeHeight, int logoWidth, int logoHeight,
                                            String format, Map<EncodeHintType, Object> ENCODE_HINTS) throws WriterException, IOException {
    BitMatrix bitMatrix = createBitMatrix(text, BarcodeFormat.QR_CODE, qrCodeWidth, qrCodeHeight, ENCODE_HINTS);
    /* 生成二维码的bufferedImage */
    BufferedImage qrcode = MatrixToImageWriter.toBufferedImage(bitMatrix);
    /* 创建图片构件对象 */
    Thumbnails.Builder<BufferedImage> builder = Thumbnails.of(new BufferedImage(qrCodeWidth, qrCodeHeight, BufferedImage.TYPE_INT_RGB));
    BufferedImage logo = ImageIO.read(logoInputStream);
    BufferedImage logoImage = Thumbnails.of(logo).size(logoWidth, logoHeight).asBufferedImage();
    /* 设置logo水印位置居中,不透明  */
    builder.watermark(Positions.CENTER, qrcode, 1F)
            .watermark(Positions.CENTER, logoImage, 1F)
            .scale(1F)
            .outputFormat(format);
    return builder;
}
 
Example #10
Source File: ImageUtil.java    From framework with Apache License 2.0 5 votes vote down vote up
/**
 * Description: 缩放图片<br>
 * 
 * @author 王伟 <br>
 * @param source <br>
 * @param dist <br>
 * @param height <br>
 * @throws UtilException <br>
 */
public static void pictureZoom(final String source, final String dist, final int height) throws UtilException {
    String tempDist = dist;
    try {
        Builder<BufferedImage> file = Thumbnails.of(cutByShort(source));
        if (source.toLowerCase().indexOf("jpg") == -1 || source.toLowerCase().indexOf("jpeg") == -1) {
            file.outputFormat("jpg");
            tempDist = dist.substring(0, dist.lastIndexOf("."));
        }
        file.outputQuality(DEFAULT_QUALITY).height(height).toFile(tempDist);
    }
    catch (Exception e) {
        throw new UtilException(ErrorCodeDef.IMAGE_ZOOM_10020, e);
    }
}
 
Example #11
Source File: ImageUtils.java    From mySpringBoot with Apache License 2.0 5 votes vote down vote up
/**
 * 转换图片格式,将流写入到输出流
 */
public static void generateOutputstream(){
    try(OutputStream outputStream = new FileOutputStream("data/2016010208_outputstream.png")) {
        Thumbnails.of("data/2016010208.jpg").
                size(500,500).
                // 转换格式
                outputFormat("png").
                // 写入输出流
                toOutputStream(outputStream);
    } catch (IOException e) {
        logger.error(e.getMessage());
    }
}
 
Example #12
Source File: ImageUtils.java    From mySpringBoot with Apache License 2.0 5 votes vote down vote up
/**
 * 使用给定的图片生成指定大小的图片
 */
public static void generateFixedSizeImage(){
    try {
        Thumbnails.of("C:\\Users\\Administrator\\Desktop\\微信图片_20180129100019.jpg").size(80,80).toFile("C:\\Users\\Administrator\\Desktop\\newmeinv.jpg");
    } catch (IOException e) {
        logger.error(e.getMessage());
    }
}
 
Example #13
Source File: ImageUtil.java    From newblog with Apache License 2.0 5 votes vote down vote up
public static File thimage(File file) {
    try {
        System.out.println(FileUtils.sizeOf(file));
        if (FileUtils.sizeOf(file) < 2000 * 1000) {
            return file;
        }
        Thumbnails.of(file).scale(1f).outputQuality(0.25f).toFile(file);
    } catch (Exception e) {
        logger.error("图片缩放错误:" + e);
    }
    return file;
}
 
Example #14
Source File: ThumbImageTest.java    From FastDFS_Client with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * PNG生成缩略图背景为黑色问题
 *
 * @throws IOException
 */
@Test
public void testImage() throws IOException {
    InputStream in = TestUtils.getFileInputStream(TestConstants.FLY_IMAGE_FILE);
    File file = new File("test.png");
    OutputStream out = new FileOutputStream(file);
    Thumbnails
            .of(in)
            .size(200, 200)
            .imageType(BufferedImage.TYPE_INT_ARGB)  //不加入这句就是黑色
            .toOutputStream(out);
    IOUtils.closeQuietly(in);
    IOUtils.closeQuietly(out);
}
 
Example #15
Source File: StringUtils.java    From mySSM with MIT License 5 votes vote down vote up
public boolean thumbnails(String path, String save) {
//        String random = getRandom();
//        StringBuilder stringBuilder = new StringBuilder();
//        stringBuilder.append("D:/image/cc/");
//        stringBuilder.append(random);
//        stringBuilder.append(new Date().getTime());
//        stringBuilder.append(".jpg");
        try {
            Thumbnails.of(path).size(215, 229).toFile(save);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }
 
Example #16
Source File: ImageResizingService.java    From fredbet with Creative Commons Attribution Share Alike 4.0 International 5 votes vote down vote up
public byte[] minimizeToSize(byte[] imageBinary, int size, Rotation rotation,
		ThumbnailsBuilderCallback byteArrayConverter) {
	if (size == 0) {
		throw new IllegalArgumentException("Given size must be greather than 0!");
	}
	try (ByteArrayInputStream byteIn = new ByteArrayInputStream(imageBinary);
			ByteArrayOutputStream byteOut = new ByteArrayOutputStream()) {

		BufferedImage bufferedImage = ImageIO.read(byteIn);
		if (bufferedImage.getWidth() <= size && bufferedImage.getHeight() <= size) {
			log.info(
					"The original image does have the prefered size of {} or is smaller than that. Do not change image size. image with: {}, image height: {}",
					size, bufferedImage.getWidth(), bufferedImage.getHeight());
			return imageBinary;
		}

		Builder<BufferedImage> builder = Thumbnails.of(bufferedImage);
		byteArrayConverter.doWithBuilder(builder);

		if (Rotation.LEFT.equals(rotation)) {
			builder.rotate(-90);
		} else if (Rotation.RIGHT.equals(rotation)) {
			builder.rotate(90);
		}

		builder.outputFormat("JPEG").toOutputStream(byteOut);
		return byteOut.toByteArray();
	} catch (Exception e) {
		log.error(e.getMessage(), e);
		return null;
	}
}
 
Example #17
Source File: ThumbUtil.java    From netty-file-parent with Apache License 2.0 5 votes vote down vote up
/**
 * 利用Thumbnailator生成缩略图
 * 
 * @author liuyuanxian
 */
public void createThumbImage() {
	//asBufferedImage() 返回BufferedImage
	try {
		BufferedImage thumbnail = Thumbnails.of(inPutFile) 
				.size(width, height).keepAspectRatio(proportion)
				.asBufferedImage();
		ImageIO.write(thumbnail, "jpg", outPutFile);
	} catch (IOException e) {
		e.printStackTrace();
	} 

}
 
Example #18
Source File: Thumbnailator.java    From maven-framework-project with MIT License 5 votes vote down vote up
/**
 * 指定大小进行缩放 
 */
@Test
public void example1() throws Exception{
	//size(宽度, 高度)
	/*  
	 * 若图片横比200小,高比300小,不变  
	 * 若图片横比200小,高比300大,高缩小到300,图片比例不变  
	 * 若图片横比200大,高比300小,横缩小到200,图片比例不变  
	 * 若图片横比200大,高比300大,图片按比例缩小,横为200或高为300  
	 */ 
	Thumbnails.of("src/main/resources/example.jpg").size(200, 300).toFile("src/main/resources/200x300.jpg");
	Thumbnails.of("src/main/resources/example.jpg").size(2560, 2048).toFile("src/main/resources/2560x2048.jpg");

}
 
Example #19
Source File: ImageUtils.java    From markdown-image-kit with MIT License 5 votes vote down vote up
/**
 * Compress.
 *
 * @param in      the in
 * @param out     the out
 * @param percent the percent
 */
public static void compress(InputStream in, OutputStream out, int percent) {
    try {
        Thumbnails.of(in)
            .scale(1f)
            .outputQuality(percent * 1.0 / 100)
            .toOutputStream(out);
    } catch (IOException e) {
        log.trace("", e);
    }
}
 
Example #20
Source File: ImageUtils.java    From mySpringBoot with Apache License 2.0 5 votes vote down vote up
/**
 * 按比例缩放图片
 */
public static void generateScale(){
    try {
        Thumbnails.of("data/2016010208.jpg").
                // 图片缩放80%, 不能和size()一起使用
                scale(0.8).
                // 图片质量压缩80%
                outputQuality(0.8).
                toFile("data/2016010208_scale.jpg");
    } catch (IOException e) {
        logger.error(e.getMessage());
    }
}
 
Example #21
Source File: AttachmentService.java    From wetech-cms with MIT License 5 votes vote down vote up
private void addFile(Attachment a,InputStream is) throws IOException {
		//进行文件的存储
		String realPath = SystemContext.getRealPath();
		String path = realPath+"/resources/upload/";
		String thumbPath = realPath+"/resources/upload/thumbnail/";
		File fp = new File(path);
		File tfp = new File(thumbPath);
//		System.out.println(fp.exists());
//		System.out.println(tfp.exists());
		if(!fp.exists()) fp.mkdirs();
		if(!tfp.exists()) tfp.mkdirs();
		path = path+a.getNewName();
		thumbPath = thumbPath+a.getNewName();
//		System.out.println(path+","+thumbPath);
		if(a.getIsImg()==1) {
			BufferedImage oldBi = ImageIO.read(is);
			int width = oldBi.getWidth();
			Builder<BufferedImage> bf = Thumbnails.of(oldBi);
			if(width>IMG_WIDTH) {
				bf.scale((double)IMG_WIDTH/(double)width);
			} else {
				bf.scale(1.0f);
			}
			bf.toFile(path);
			//缩略图的处理
			//1、将原图进行压缩
			BufferedImage tbi = Thumbnails.of(oldBi)
						.scale((THUMBNAIL_WIDTH*1.2)/width).asBufferedImage();
			//2、进行切割并且保持
			Thumbnails.of(tbi).scale(1.0f)
				.sourceRegion(Positions.CENTER, THUMBNAIL_WIDTH, THUMBNAIL_HEIGHT)
				.toFile(thumbPath);
		} else {
			FileUtils.copyInputStreamToFile(is, new File(path));
		}
	}
 
Example #22
Source File: ImageUtil.java    From springboot-learn with MIT License 5 votes vote down vote up
/**
 * 生成缩略图到指定的目录
 *
 * @param scale    图片缩放率
 * @param pathname 缩略图保存目录
 * @param files    要生成缩略图的文件列表
 * @throws IOException
 */
public static List<String> generateThumbnail2Directory(double scale, String pathname, String... files) throws IOException {
    Thumbnails.of(files)
            // 图片缩放率,不能和size()一起使用
            .scale(scale)
            // 缩略图保存目录,该目录需存在,否则报错
            .toFiles(new File(pathname), Rename.SUFFIX_HYPHEN_THUMBNAIL);
    List<String> list = new ArrayList<>(files.length);
    for (String file : files) {
        list.add(appendSuffix(file, SUFFIX));
    }
    return list;
}
 
Example #23
Source File: ImageProcessor.java    From elepy with Apache License 2.0 5 votes vote down vote up
public byte[] processImage(Request request, FileUpload file) throws ExecutionException {

        final var size = intParam("size", request);
        final var width = intParam("width", request);
        final var height = intParam("height", request);
        final var scale = Optional.ofNullable(request.queryParams("scale")).map(Double::parseDouble);

        final var imageKey = new ImageKey(file.getName(),
                size.orElse(null),
                width.orElse(null),
                height.orElse(null),
                scale.orElse(null)
        );

        final var scaledImage = cachedImages.get(imageKey, () -> {
            final var original = ImageIO.read(file.getContent());
            final var thumbnailBuilder = Thumbnails.of(original);

            size.ifPresent(s -> thumbnailBuilder.size(s, s));

            width.ifPresent(thumbnailBuilder::width);

            height.ifPresent(thumbnailBuilder::height);

            scale.ifPresent(thumbnailBuilder::scale);

            return thumbnailBuilder.asBufferedImage();
        });

        return toBytes(scaledImage, file.getContentType());
    }
 
Example #24
Source File: DefaultFastFileStorageClient.java    From FastDFS_Client with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * 根据传入尺寸生成缩略图
 *
 * @param inputStream
 * @param thumbImage
 * @return
 * @throws IOException
 */
private ByteArrayInputStream generateThumbImageBySize(InputStream inputStream,
                                                      ThumbImage thumbImage) throws IOException {
    LOGGER.debug("根据传入尺寸生成缩略图");
    // 在内存当中生成缩略图
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    //@formatter:off
    Thumbnails
            .of(inputStream)
            .size(thumbImage.getWidth(), thumbImage.getHeight())
            .imageType(BufferedImage.TYPE_INT_ARGB)
            .toOutputStream(out);
    //@formatter:on
    return new ByteArrayInputStream(out.toByteArray());
}
 
Example #25
Source File: Thumbnailator.java    From maven-framework-project with MIT License 5 votes vote down vote up
/**
 * 输出到OutputStream
 */
@Test
public void example8() throws Exception{
	//toOutputStream(流对象)
	OutputStream os = new FileOutputStream("src/main/resources/a380_1280x1024_OutputStream.png");
	Thumbnails.of("src/main/resources/example.jpg") 
			.size(1280, 1024)
	        .toOutputStream(os);

}
 
Example #26
Source File: DefaultFastFileStorageClient.java    From FastDFS_Client with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * 根据传入尺寸生成缩略图
 *
 * @param inputStream
 * @param thumbImage
 * @return
 * @throws IOException
 */
private ByteArrayInputStream generateThumbImageBySize(InputStream inputStream,
                                                      ThumbImage thumbImage) throws IOException {
    LOGGER.debug("根据传入尺寸生成缩略图");
    // 在内存当中生成缩略图
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    //@formatter:off
    Thumbnails
            .of(inputStream)
            .size(thumbImage.getWidth(), thumbImage.getHeight())
            .imageType(BufferedImage.TYPE_INT_ARGB)
            .toOutputStream(out);
    //@formatter:on
    return new ByteArrayInputStream(out.toByteArray());
}
 
Example #27
Source File: ImageUtils.java    From JavaLib with MIT License 5 votes vote down vote up
/**
 * 图片压缩,生成压缩图片文件
 * @param url 图片URL
 * @param thumbnail 缩略图保存位置
 * @param scale 压缩比
 */
public static void compress(URL url, String thumbnail, int scale) {
    try {
        Thumbnails
                .of(url)
                .scale(scale)
                .toFile(thumbnail);
    } catch (IOException e) {
        // e.printStackTrace();
    }
}
 
Example #28
Source File: LocalFileStorage.java    From leo-im-server with Apache License 2.0 5 votes vote down vote up
/**
 * 保存预览图片
 * @param key
 * @param fileName
 * @param data
 * @param width
 * @param height
 * @return
 */
@Override
public short[] saveThumb(String key, String fileName, byte[] data, int width, int height) {
    StringBuilder newFile = new StringBuilder(256);
    newFile.append(System.getProperty("file.settings.directory"));
    if(newFile.length() == 0) {
        throw new NoSuchSettingException("file.settings.directory");
    }
    if(key != null && !key.trim().isEmpty()) {
        newFile.append("/").append(key);
    }
    // 判断目录是否存在
    File dir = new File(newFile.toString());
    if(!dir.exists()) {
        dir.mkdir();
    }
    
    newFile.append("/").append(fileName);
    InputStream is = new ByteArrayInputStream(data);
    try {
        Thumbnails.of(is).size(width, height).toFile(newFile.toString());
        File picture = new File(newFile.toString());
        BufferedImage sourceImage = ImageIO.read(new FileInputStream(picture));
        return new short[] { (short)sourceImage.getWidth(), (short)sourceImage.getHeight() };
    } catch (IOException e) {
        logger.error(e.getMessage());
        return null;
    }
}
 
Example #29
Source File: LocalAvatarStorage.java    From leo-im-server with Apache License 2.0 5 votes vote down vote up
/**
 * 保存头像
 * @param userId
 * @param fileType
 * @param data
 * @param width
 * @param height
 * @return
 */
@Override
public boolean save(String userId, String fileType, byte[] data, int width, int height) {
    StringBuilder newFile = new StringBuilder(256);
    newFile.append(System.getProperty("file.settings.directory"));
    if(newFile.length() == 0) {
        throw new NoSuchSettingException("file.settings.directory");
    }
    if(userId != null && !userId.trim().isEmpty()) {
        newFile.append("/").append(userId);
    }
    // 判断目录是否存在
    File dir = new File(newFile.toString());
    if(!dir.exists()) {
        dir.mkdir();
    }
    
    newFile.append("/avatar").append(width).append("x").append(height).append(".").append(fileType);
    InputStream is = new ByteArrayInputStream(data);
    try {
        Thumbnails.of(is).size(width > 70 ? width : width * 2, height > 70 ? height : height * 2).toFile(newFile.toString());
    } catch (IOException e) {
        logger.error(e.getMessage());
        return false;
    }
    return true;
}
 
Example #30
Source File: ImagesUtils.java    From PPT-Templates with Apache License 2.0 5 votes vote down vote up
@SneakyThrows
private static byte[] resize(byte[] imageData, String targetFormat, int width, int height,
		boolean crop, float qualityFactor, double qualityMultiplicator) {
	ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
	Builder<? extends InputStream> builder = Thumbnails
		.of(new ByteArrayInputStream(imageData))
		.outputQuality(qualityFactor)
		.size(
			(int) Math.round(width * qualityMultiplicator),
			(int) Math.round(height * qualityMultiplicator)
		);

	if(crop) {
		builder.crop(Positions.CENTER);
	}

	try {
		builder
			.outputFormat(targetFormat)
			.toOutputStream(byteArrayOutputStream);
	} catch (IOException e) {
		logger.error("Cannot resize image to format {}", targetFormat, e);
		return null;
	}

	return byteArrayOutputStream.toByteArray();
}