tadeuespindola

Leandro Amorim Batista

Jan 6th, 2021
257
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.92 KB | None | 0 0
  1. public String salvar() throws IOException{
  2.         try {
  3.            
  4.             /*processar imagem*/
  5.             /*esse método salva a imagem original*/
  6.             byte[] imagemByte = null;
  7.             if (arquivoFoto != null) {
  8.                 imagemByte = getByte(arquivoFoto.getInputStream());            
  9.             }
  10.             if (imagemByte != null && imagemByte.length > 0) {
  11.                 produto.setFotoIconBase64Original(imagemByte);
  12.                
  13.                 /*transformar em um bufferimage*/
  14.                 BufferedImage bufferedImage = ImageIO.read(new ByteArrayInputStream(imagemByte));
  15.                
  16.                 /*pega o tipo da imagem*/
  17.                 int type = bufferedImage.getType() == 0? BufferedImage.TYPE_INT_ARGB : bufferedImage.getType();
  18.                
  19.                 int largura = 200;
  20.                 int altura = 200;
  21.                
  22.                 /*criando a miniatura*/
  23.                 BufferedImage resizedImage = new BufferedImage(largura, altura, type);
  24.                 Graphics2D graphics2d = resizedImage.createGraphics();
  25.                 graphics2d.drawImage(bufferedImage, 0, 0, largura, altura, null);
  26.                 graphics2d.dispose();
  27.                
  28.                 /*escrever novamente a imagem em tamanho menor*/
  29.                 ByteArrayOutputStream arrayOutputStream = new ByteArrayOutputStream();
  30.                 String extensao = arquivoFoto.getContentType().split("\\/")[1];//retorna a extensao
  31.                 ImageIO.write(resizedImage, extensao, arrayOutputStream);
  32.                
  33.                 String miniImagem =
  34.                         "data:" + arquivoFoto.getContentType() + ";base64," + DatatypeConverter.printBase64Binary(arrayOutputStream.toByteArray());
  35.                 /*fim do processamento de imagem*/
  36.                
  37.                 produto.setFotoIconBase64(miniImagem);
  38.                 produto.setExtensao(extensao);
  39.             }
  40.             produto = daoGeneric.merge(produto);
  41.             if (produto != null) {
  42.                 this.carregarListaProdutos();
  43.                 this.novo();
  44.                 Messages.addGlobalInfo("Registro salvo com sucesso!");
  45.             } else {
  46.                 Messages.addGlobalInfo("Não foi possível salvar o registro!");
  47.             }      
  48.         } catch (Exception e) {
  49.             e.printStackTrace();
  50.             Messages.addFlashGlobalError("Ocorreu um erro ao tentar salvar um novo registro!");
  51.         }
  52.         return "";
  53.     }
Add Comment
Please, Sign In to add comment