繁体   English   中英

如何在java中将图像url转换为字节数组?

[英]How to convert Image url to Byte Array in java?

我正在尝试使用 aws 图像识别 api 制作网络爬虫。 所以我必须将图像转换为字节数组才能使 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();
    }

}

您应该使用 URL 类来执行 openStream。 我希望照片是图像的位置。

new URL(photo).openStream()

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM