| | |
| | | |
| | | // PNG的压缩级别(0-9,0最快但压缩率低,9最慢但压缩率高) |
| | | if (compressionLevel >= 0) { |
| | | try { |
| | | // 先检查是否支持压缩模式 |
| | | if (param.canWriteCompressed()) { |
| | | param.setCompressionMode(ImageWriteParam.MODE_EXPLICIT); |
| | | |
| | | // 检查是否支持压缩类型设置 |
| | | String[] compressionTypes = param.getCompressionTypes(); |
| | | if (compressionTypes != null && compressionTypes.length > 0) { |
| | | // 尝试设置压缩类型 |
| | | String compressionType = compressionTypes[0]; |
| | | for (String type : compressionTypes) { |
| | | if ("Deflate".equalsIgnoreCase(type) || "PNG".equalsIgnoreCase(type)) { |
| | | compressionType = type; |
| | | break; |
| | | } |
| | | } |
| | | param.setCompressionType(compressionType); |
| | | } |
| | | |
| | | // 设置压缩质量(压缩级别转换为0.0-1.0) |
| | | float quality = Math.max(0.0f, Math.min(1.0f, compressionLevel / 9.0f)); |
| | | param.setCompressionQuality(quality); |
| | | } else { |
| | | // 如果不支持压缩模式,记录警告并继续使用默认设置 |
| | | log.warn("PNG编码器不支持压缩模式,使用默认设置"); |
| | | } |
| | | } catch (UnsupportedOperationException e) { |
| | | // 捕获异常,记录警告,然后使用默认设置继续 |
| | | log.warn("设置PNG压缩参数失败: {},使用默认设置", e.getMessage()); |
| | | // 重置参数为默认值 |
| | | param = writer.getDefaultWriteParam(); |
| | | } |
| | | param.setCompressionMode(ImageWriteParam.MODE_EXPLICIT); |
| | | param.setCompressionType("Deflate"); |
| | | param.setCompressionQuality(Math.max(0.0f, Math.min(1.0f, compressionLevel / 9.0f))); |
| | | } |
| | | |
| | | try { |
| | | writer.setOutput(new MemoryCacheImageOutputStream(output)); |
| | | writer.write(null, new IIOImage(image, null, null), param); |
| | | } catch (Exception e) { |
| | | log.warn("使用ImageWriter写入PNG失败: {},回退到ImageIO.write", e.getMessage()); |
| | | // 回退到简单的ImageIO.write |
| | | ImageIO.write(image, "png", output); |
| | | } finally { |
| | | writer.dispose(); |
| | | } |
| | | writer.setOutput(new MemoryCacheImageOutputStream(output)); |
| | | writer.write(null, new IIOImage(image, null, null), param); |
| | | writer.dispose(); |
| | | } |
| | | |
| | | |