0

私のアプリケーションにはアップロード機能があります。そのために、Apache-commonsファイルのアップロードとSpringマルチパートを使用し、イメージをディレクトリフォルダーに保存しました(プロジェクトコンテキスト内ではありません)。私が立ち往生した問題は、画像を取得してjspでレンダリングすることです。バッファリングされた画像とImageIOを使用してそのフォルダーから画像を読み込もうとしましたが、imgタグを使用してjspでレンダリングする方法がわかりません。どんな助けでも大歓迎です。

//Code for reading 
BufferedImage im=ImageIO.read(new File(imagePath));
4

1 に答える 1

3

ようやく img タグを使って Web ブラウザに画像を表示できるようになりました。私が今従うステップ: 1. BufferedImage を使用して画像を読み取ります。2. ByteArrayOutputStream を使用して bufferedImage をバイトに変換しました。3. apache commons codec lib を使用してそのストリームを Base64 にエンコードし、文字列に変換します 4. img タグを使用して html で画像のこの文字列値を返します

 //Pseudo Code 
    BufferedImage bufferedImage=ImageIO.read(new File(imagePath));

   //imageDao contains the image name that i stored in the database
   String []formatSplit=imageDao.split("\\.");

   if(formatSplit.length==2){
     String format=formatSplit[1];

     //ImageUtility is class that contain code for converting bufferedimage to string
     String traineeImage=ImageUtility.encodeToString(bufferedImage,format );

     model.addAttribute("imagePath", traineeImage);
    }


    //ImageUtilty class -method

     public static String encodeToString(BufferedImage image, String type) {

        String imageString=null;
        String encodedImage=null;
        ByteArrayOutputStream bos = new ByteArrayOutputStream();

        try {

            ImageIO.write(image, type, bos);
            byte[] imageBytes = bos.toByteArray();


            encodedImage=org.apache.commons.codec.binary.Base64.encodeBase64String(imageBytes);

            imageString = "data:image/"+type+";base64,"+encodedImage;

            bos.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return imageString;
    }

そして、imgタグのsrc属性で、imageStringを渡しましたが、うまくいきました。解決策を見つけるために、私が探していたものを達成するのに役立つスタックオーバーフローや他のブログから見つけたヒントがたくさんあります。ありがとう。

于 2013-11-28T07:03:49.283 に答える