在我的JSF应用程序中,我想拖放JPEG图片(30张图片大小约为10Mo),我正面对一个慢速充电页面和图片。 我正在使用以下代码压缩这些图片:
public void reduceImageQuality(int sizeThreshold, UploadedFile file, String destImg) throws Exception {
float quality = 0.05f;
long fileSize = file.getSize();
if (fileSize <= sizeThreshold) {
System.out.println("Image file size is under threshold");
return;
}
Iterator iter = ImageIO.getImageWritersByFormatName("jpeg");
ImageWriter writer = (ImageWriter) iter.next();
ImageWriteParam iwp = writer.getDefaultWriteParam();
iwp.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
BufferedImage originalImage = ImageIO.read(file.getInputstream());
IIOImage image = new IIOImage(originalImage, null, null);
float percent = 0.01f; // 10% of 1
while (fileSize > sizeThreshold) {
if (percent >= quality) {
percent = percent * 0.1f;
}
quality -= percent;
File fileOut = new File(destImg);
if (fileOut.exists()) {
fileOut.delete();
}
try (FileImageOutputStream output = new FileImageOutputStream(fileOut)) {
writer.setOutput(output);
iwp.setCompressionQuality(quality);
writer.write(null, image, iwp);
File fileOut2 = new File(destImg);
long newFileSize = fileOut2.length();
if (newFileSize == fileSize) {
// cannot reduce more, return
break;
} else {
fileSize = newFileSize;
}
System.out.println("quality = " + quality + ", new file size = " + fileSize);
}
}
writer.dispose();
}
对于我的XHTML代码:
<h:form id="firstGenForm" enctype="multipart/form-data" >
<h:panelGrid columns="1" style="margin-left:40px;">
<p:outputPanel id="imageForPenetrationPointPublic" styleClass="slot">
<h:panelGrid columns="1" rendered="#{generationTdeEbmMB.selectedImageForPenetrationPointPublic!= null}">
<p:graphicImage url="/images/#{generationTdeEbmMB.selectedImageForPenetrationPointPublic}" style="width: 100%;height: 260px;"/>
</h:panelGrid>
</p:outputPanel>
<p:droppable for="imageForPenetrationPointPublic" tolerance="fit" activeStyleClass="ui-state-highlight" datasource=":availablePictureForm:availablePicturesDGrid" onDrop="handleDrop">
<p:ajax listener="#{generationTdeEbmMB.onImageForPenetrationPointPublicDrop}" update="imageForPenetrationPointPublic " />
</p:droppable>
</h:panelGrid>
</h:form>
<h:form id="availablePictureForm" >
<p:fieldset legend="Photos disponibles " rendered="#{generationTdeEbmMB.uploadedImageNameList.size() != 0}">
<p:scrollPanel style="width:400px;height: 600px;">
<p:dataGrid id="availablePicturesDGrid" value="#{generationTdeEbmMB.uploadedImageNameList}" var="imageName" columns="3" emptyMessage="Aucune photo trouvée.">
<p:panel id="pnl" header="#{imageName}" style="text-align:center">
<h:panelGrid columns="1" style="width:20%">
<p:graphicImage url="/images/#{imageName}" style="width: 120px;height: 110px;"/>
</h:panelGrid>
</p:panel>
<p:draggable for="pnl" proxy="true" revert="true" helper="clone" handle=".ui-panel-content" stack=".ui-panel"/>
</p:dataGrid>
</p:scrollPanel>
</p:fieldset>
</h:form>
但缓慢的问题仍然存在。如果不纠正这个问题,我什么也做不了。 我正在使用JSF 2.1和PrimeFaces 3.5
欢迎任何建议或想法。
非常感谢提前。