如何在Java中将图像URL转换为字节数组?

时间:2019-01-30 15:32:44

标签: java

我正在尝试使用AWS Image Recognition API创建Webscrapper。所以我必须将图像转换为字节数组,以使api工作。但是,我在说The method openStream() is undefined for the type String时遇到了一些错误。如果我使用本地图像文件,则工作正常。有人可以帮帮我吗 ? 谢谢

public class HelloAppEngine extends HttpServlet{

    /**
     * 
     * 
     * 
     * 
     * 
     * 
     * 
     */
         // where jsoup images are stored 

    static ArrayList<String> testImages = new ArrayList<String>();

    public static void getimages() {

        String photo =  testImages.get(0);



    ByteBuffer imageBytes = null;
    try (InputStream inputStream = photo.openStream())) {
        imageBytes = ByteBuffer.wrap(IOUtils.toByteArray(inputStream));
    }

    catch (IOException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }


    AmazonRekognition rekognitionClient = AmazonRekognitionClientBuilder.defaultClient();

    DetectLabelsRequest request = new DetectLabelsRequest()
            .withImage(new Image()
                    .withBytes(imageBytes))
            .withMaxLabels(10)
            .withMinConfidence(77F);

    try {

        DetectLabelsResult result = rekognitionClient.detectLabels(request);
        List <Label> labels = result.getLabels();

        System.out.println("Detected labels for " + photo);
        for (Label label: labels) {
           System.out.println(label.getName() + ": " + label.getConfidence().toString());
        }

    } catch (AmazonRekognitionException e) {
        e.printStackTrace();
    }

}

1 个答案:

答案 0 :(得分:0)

您应该使用URL类做的OpenStream。我希望照片是图像的位置。

new URL(photo).openStream()