【问题标题】:How to save an image in byte Array and get back bytearray into image in grails?如何将图像保存在字节数组中并将字节数组返回到 grails 中的图像中?
【发布时间】:2013-10-11 06:45:34
【问题描述】:

我想将图像保存在字节数组中.. 并保存到 mongoDb 数据库中.. 并将字节数组返回到图像文件中 并显示在 .GSP 页面上

class Profile{
    static mapWith = "mongo"

    String firstname
    String lastname
    byte[] imgpath
}

控制器

def saveimage{
    File filepath = new File("C:\\man-of-steel-theme.jpg");


   def encodedData = filepath.bytes;
   profile.imgpath=encodedData;
   profile.save();
}

在此不确定是否将正确的字节数组保存到 mongodb 并且无法获取图像文件

【问题讨论】:

  • "不确定字节数组是否正确" -> 你确认了吗? “无法获取图片文件” -> 你检查了检索码吗?
  • 字节数组还有其他选择吗..因为我看到大多数人都在字节数组中保存图像...即使我不确定..你会指导我...将图像保存在 mongoDb 中,字符串路径除外..
  • 我在努力,但你不配合。
  • 对不起.. 请指导我如何保存图像?如果您有其他方法可以做到这一点...请告诉我..我会尝试按照您的方式进行
  • 当你一直无视我的第一条评论时,我无能为力。

标签: mongodb grails grails-2.0 grails-controller


【解决方案1】:

也许这对你有帮助

    import java.awt.Graphics2D
    import java.awt.image.BufferedImage

    import javax.imageio.ImageIO
    import javax.imageio.stream.ImageInputStream
    import javax.imageio.stream.MemoryCacheImageInputStream

    class xyzClass {
        def zabcdef(){
            org.springframework.web.multipart.commons.CommonsMultipartFile multipartfile = request.getFile('picture')
            if (!multipartfile || multipartfile.getContentType() != 'image/jpeg') {
                render("${message(code:'error.wrong.file.type')}: jpeg")
                return;
            }

            ImageInputStream iis = new MemoryCacheImageInputStream(multipartfile.getInputStream())
            BufferedImage image = ImageIO.read(iis)

            storeImage(image,"foto")
        }

    }



    private storeImage(BufferedImage image, String name) {
        ByteArrayOutputStream os = new ByteArrayOutputStream()
        ImageIO.write(image, "jpg", os)
        byte[] buf = os.toByteArray()
        InputStream is = new ByteArrayInputStream(buf)
        //store
    }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-06-11
    • 1970-01-01
    • 1970-01-01
    • 2014-05-26
    • 2019-04-16
    • 1970-01-01
    相关资源
    最近更新 更多