gpt4 book ai didi

java - 如何在 Grails 中始终将 CommonsMultipartFile 保存为 JPG(并检查它是否是图像)

转载 作者:太空宇宙 更新时间:2023-11-04 07:29:15 24 4
gpt4 key购买 nike

它有效:

查看(普惠制):

<g:uploadForm action="upload">
<input type="file" name="myImageFile" />
<input type="submit" />
</g:uploadForm>

Controller :

def destination = "D:\\someFolder\\image.jpg";
def f = request.getFile('myImageFile')
f.transferTo(new File(destination))
response.sendError(200, 'Done')

但是我总是想将其转换为 JPG 图像。所以我尝试了:

def destination = "D:\\someFolder\\image.jpg";
PlanarImage inputfile = JAI.create("FileLoad", f);
JAI.create("filestore",inputfile,destination,"JPEG");

这是错误:

FileLoad - 参数值类 (org.springframework.web.multipart.commons.CommonsMultipartFile) 不是参数“文件名”的参数类 (java.lang.String) 的实例。堆栈跟踪如下:

到目前为止,我唯一的解决方案是在检查图像是否是图像后照常保存图像(感谢@james-kleeh)。然后使用 JAI.create 加载它并执行操作。最后删除原始图像。

我还想知道如何检查上传的文件是否是图像

最佳答案

GSP 代码与我在问题中发布的代码相同。

Controller 代码如下:

import javax.media.jai.*;
...

def f = request.getFile('myFile')
def okContentTypes = ['image/png', 'image/jpeg', 'image/jpg', 'image/gif']

if (!okContentTypes.contains(f.getContentType())) {
// TODO Tell user: "Image type must be one of: ${okContentTypes}"
}

else {
def destination = "D:\\someFolder\\image.jpg";
byte[] source = f.bytes;
SeekableStream inputStream = new ByteArraySeekableStream(source);
RenderedOp image = JAI.create("stream", inputStream)
JAI.create("filestore",image,destination,"JPEG"); // Destination directory must exist (D:\someFolder\)
}

我希望它对某人有用!

关于java - 如何在 Grails 中始终将 CommonsMultipartFile 保存为 JPG(并检查它是否是图像),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18023348/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com