以下是我的问题的详细信息:
问题:我正在使用RestEasy从Multipart Form InputStream上传调整大小的缩略图。要提供给Scalr.resize的BufferedImage对象返回 NULL 值。在下面的代码中, BufferedImage img始终为NULL 。
你能帮我弄明白我怎样才能做到这一点。
我的代码片段:
import javax.inject.Inject;
import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.core.MediaType;
import org.jboss.resteasy.annotations.providers.multipart.MultipartForm;
import org.jboss.resteasy.plugins.providers.IIOImageProviderHelper;
import org.neo4j.graphdb.GraphDatabaseService;
import com.kryptonite.aws.AWSHelper;
import com.kryptonite.utils.DAO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import org.imgscalr.Scalr;
:
:
:
:
@POST
@Consumes( MediaType.MULTIPART_FORM_DATA )
public String uploadImage(@MultipartForm InputStream image) throws IOException {
BufferedImage img = ImageIO.read(image);
BufferedImage thumbnail = Scalr.resize(img,Scalr.Method.AUTOMATIC, Scalr.Mode.FIT_TO_WIDTH,150, 100, Scalr.OP_ANTIALIAS);
thumbnail.createGraphics().drawImage(thumbnail, 0, 0, null);
ImageIO.write(thumbnail, "jpg", new File("/temp/test.jpg"));
return key;
}
答案 0 :(得分:0)
使用MediaType multipart/form-data
,您的请求有效负载会分成多个部分,可能如下所示:
POST /some-resource HTTP/1.1
Content-Type: multipart/form-data; boundary=AaB03x
--AaB03x
Content-Disposition: form-data; name="description"
... description of the image ...
--AaB03x
Content-Disposition: form-data; name="file"; filename="img1.jpg"
Content-Type: image/jpeg
... content of img1.jpg ...
--AaB03x--
如果您只是使用请求的InputStream
,则需要自行解析,但您通常不想使用MultipartFormDataInput
或者您尝试@MultipartForm
。在这里,您需要将请求有效负载映射到POJO,如下所示:
public class ImgUpload {
@FormParam("description")
private String description;
@FormParam("file")
@PartType("image/jpeg")
private InputStream file;
}
请同时查看documentation或this example。
答案 1 :(得分:0)
经过一番挖掘后,这对我有用:
使用MultipartFormDataInput作为输入
代码看起来类似于:
Map<String, List<InputPart>> uploadForm = images.getFormDataMap();
List<InputPart> inputParts = uploadForm.get("uploadedImage");
InputStream inputStream = null;
BufferedImage reimg = null;
for (InputPart inputPart : inputParts) {
try {
MultivaluedMap<String, String> header = inputPart.getHeaders();
if (fileName == null){
key = "nutped_"+ new Date().getTime()+"_"+getFileName(header);
} else {
key=fileName;
}
inputStream = inputPart.getBody(InputStream.class,null);
InputStream is = new BufferedInputStream(inputStream);
reimg = Scalr.resize(ImageIO.read(is), Method.SPEED, size, OP_ANTIALIAS, OP_BRIGHTER);
} catch (IOException e) {
e.printStackTrace();
}
}
//convert BufferedImage to InputStream
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ImageIO.write(reimg, "png", baos);
InputStream isReimg = new ByteArrayInputStream(baos.toByteArray());