Using Wicket to display an image stored as BLOB in

2019-04-02 14:33发布

问题:

I currently have a blob in my mysql db that contains an image. What i want is to display this image to the user.

I cannot place it in a directory structure as the blob may be anything from an image to a piece of html so there is logic involved as to whether it is a piece of html or an image etc.

I was thinking of checking the BLOB to see if it is an image and it can output it to a temporary directory then load it as a resource but then I noticed wicket has a BlobImageResource class however I am not sure how this is to be implemented and am unable to find any examples after searching on google.

Any suggestions how best to go about doing this ?

i am using wicket 6.xx and have access to spring and hibernate and am not against using third party libraries

回答1:

private byte[] blob = some data...;

to check blob is an image:

Boolean isImage = ImageIO.read(new ByteArrayInputStream(blob)) != null;
if( isImage ){
    // blob is an image...
}

create a IResource object and show in html:

IResource imageResource = new DynamicImageResource() {
                @Override
                protected byte[] getImageData(IResource.Attributes attributes) {
                    return blob;
                }
            };
Image image = new Image("wicketId", imageResource);
this.add(image);

in html file use:

<wicket:panel>
    <img wicket:id="wicketId"/>
</wicket:panel>


回答2:

Wicket code for blob image from MySql DB to HTML page

public class BlobToImage extends WebPage{

private static Blob blob;
public BlobToImage() {

    BlobImageResource blobImgSrc = new BlobImageResource() {

        @Override
        protected Blob getBlob(Attributes attributes) {             
            return blob;
        }
    };
    try {
        getBlob();
    } catch (SQLException e) {
        e.printStackTrace();
    }   

    Image img = new Image("image", blobImgSrc);
    add(img);
}

public static void getBlob() throws SQLException{
    Properties ConProps = new Properties();
    ConProps.put("user","root");
    ConProps.put("password", "root");

    Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/google_map",ConProps);
    System.out.println(conn);

    java.sql.Statement stmt = conn.createStatement();
    stmt.execute("SELECT id,image FROM images where id=1");
    ResultSet rs = stmt.getResultSet();
    while(rs.next()){
        try{
            blob = rs.getBlob("image");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

} The following HTML code helps to show the image at the webpage

    Image <img wicket:id="image"  alt="image">