下载一个存储桶中的图像列表 Java

huangapple go评论71阅读模式
英文:

Downloading a list of images from a bucket java

问题

Here's the translated code portion:

@Override
public byte[] downloadUserGalleryImages(String email) {

    UserProfile user = userRepo.findByEmail(email);
    if (Objects.isNull(user)){
        throw new UserServiceException(ErrorMessages.USER_NOT_FOUND.getErrorMessage());
    }

    String path = String.format("%s/%s/%s", BucketName.SPACE_NAME.getBucketName(),
            GALLERY_IMAGES,
            user.getUsername());
    byte[] images;
    List<byte[]> imageResults = new ArrayList<>();
    if (user.getImageGallery().size() > 0){
        user.getImageGallery().forEach(imageGallery -> {
            String imageUrl = imageGallery.getImageUrl();
            byte[] bytes = downloadUserImages(path, imageUrl);
            imageResults.add(bytes);

        });

    }
    images = new byte[imageResults.size()];
    images = imageResults.toArray(images);
    return images;
}

public byte[] downloadUserImages(String path, String key) {
    try {
        S3Object object = s3.getObject(path, key);
        return IOUtils.toByteArray(object.getObjectContent());
    } catch (AmazonServiceException | IOException e) {
        throw new IllegalStateException("Failed to download file to S3", e);
    }
}

I removed the HTML escape characters (&quot;) for better readability in the translated code.

英文:

Can some help me am trying to retrieve a list of images from s3 bucket below is my code but it's not compiling. images = imageResults.toArray(images); am getting compilation error: Cannot resolve method &#39;toArray(byte[])&#39;,

 @Override
public byte[] downloadUserGalleryImages(String email) {

    UserProfile user = userRepo.findByEmail(email);
    if (Objects.isNull(user)){
        throw new UserServiceException(ErrorMessages.USER_NOT_FOUND.getErrorMessage());
    }

    String path = String.format(&quot;%s/%s/%s&quot;, BucketName.SPACE_NAME.getBucketName(),
            GALLERY_IMAGES,
            user.getUsername());
    byte[] images;
    List&lt;byte[]&gt; imageResults = new ArrayList&lt;&gt;();
    if (user.getImageGallery().size() &gt; 0){
        user.getImageGallery().forEach(imageGallery -&gt; {
            String imageUrl = imageGallery.getImageUrl();
            byte[] bytes = downloadUserImages(path, imageUrl);
            imageResults.add(bytes);

        });

    }
    images = new byte[imageResults.size()];
    images = imageResults.toArray(images);
    return images;
}

public byte[] downloadUserImages(String path, String key) {
    try {
        S3Object object = s3.getObject(path, key);
        return IOUtils.toByteArray(object.getObjectContent());
    } catch (AmazonServiceException | IOException e) {
        throw new IllegalStateException(&quot;Failed to download file to s3&quot;, e);
    }
}
 tried to map Bytes to list but this returns only one image I gues it&#39;s because of flatMap
images = Bytes.toArray(imageResults.stream()
            .map(Bytes::asList)
            .flatMap(Collection::stream)
            .collect(Collectors.toList()));
    return images;

I must be honest am getting struggles working with bytes so your help is highly appreciated family.

答案1

得分: 1

从Oracle的javaDoc中,ArrayList的方法public T[] toArray(T[] a)期望一个泛型类型的数组。这不包括原始类型,因此byte[]会导致错误:

byte[] myBytes1 = {0,1,2,3,4};
byte[] myBytes2 = {5,6,7,8,9};

List<byte[]> imageResults = new ArrayList<>();
imageResults.add(myBytes1);
imageResults.add(myBytes2);

byte[] images;
images = new byte[imageResults.size()];
images = imageResults.toArray(images); // 找不到适合的方法toArray(byte[])

改成Byte[]来给数组一个"正确"的类型会修复这个问题,但是代码尝试将Byte数组的列表放入数组中,这是不允许的:

Byte[] myBytes1 = {0,1,2,3,4};
Byte[] myBytes2 = {5,6,7,8,9};

List<Byte[]> imageResults = new ArrayList<>();
imageResults.add(myBytes1);
imageResults.add(myBytes2);

Byte[] images;                          // 必须是Byte[],不能是byte[]
images = new Byte[imageResults.size()]; 
images = imageResults.toArray(images);  // arraycopy: element type mismatch

然而,它可以接受byte的列表并将其放入Byte数组中:

byte myByte1 = 1;
byte myByte2 = 2;

List<Byte> imageResults = new ArrayList<>();
imageResults.add(myByte1);
imageResults.add(myByte2);

Byte[] images;                          // 必须是Byte[],不能是byte[]
images = new Byte[imageResults.size()];
images = imageResults.toArray(images);

System.out.println(Arrays.toString(images));

// 输出:
// [1, 2]

它还可以接受byte数组并将其放入二维Byte数组中。注意,它们是Byte数组,而不是byte数组,因为byte[] 不能转换为 Byte[]

Byte[] myBytes1 = {0,1,2,3,4};
Byte[] myBytes2 = {5,6,7,8,9};

List<Byte[]> imageResults = new ArrayList<>();
imageResults.add(myBytes1);
imageResults.add(myBytes2);

Byte[][] images;
images = new Byte[imageResults.size()][];
images = imageResults.toArray(images);

System.out.println(Arrays.deepToString(images));

// 输出:
// [[0, 1, 2, 3, 4], [5, 6, 7, 8, 9]]

如果你需要byte[][]而不是Byte[][],你不能使用toArray()方法。而是遍历ArrayList:

byte[] myBytes1 = {0,1,2,3,4};
byte[] myBytes2 = {5,6,7,8,9};

List<byte[]> imageResults = new ArrayList<>();
imageResults.add(myBytes1);
imageResults.add(myBytes2);

byte[][] images = new byte[imageResults.size()][];
for (int i = 0; i < imageResults.size(); i++){
  images[i] = imageResults.get(i);
}

// 循环的替代方法:
// IntStream.range(0, imageResults.size()).forEach(i -> images[i] = imageResults.get(i));

System.out.println(Arrays.deepToString(images));

// 输出:
// [[0, 1, 2, 3, 4], [5, 6, 7, 8, 9]]
英文:

From Oracle's javaDoc the method public <T> T[] toArray?(T[] a) of ArrayList expects an array of a generic type. This excludes primitives, so byte[] will give an error:

byte[] myBytes1 = {0,1,2,3,4};
byte[] myBytes2 = {5,6,7,8,9};

List&lt;byte[]&gt; imageResults = new ArrayList&lt;&gt;();
imageResults.add(myBytes1);
imageResults.add(myBytes2);

byte[] images;
images = new byte[imageResults.size()];
images = imageResults.toArray(images); // no suitable method found for toArray(byte[])

<br/>

Changing to Byte[] to give the array a "proper" type, will fix that, but the code is trying to take a list of Byte arrays and put those arrays into an array, which it cannot do:

Byte[] myBytes1 = {0,1,2,3,4};
Byte[] myBytes2 = {5,6,7,8,9};

List&lt;Byte[]&gt; imageResults = new ArrayList&lt;&gt;();
imageResults.add(myBytes1);
imageResults.add(myBytes2);

Byte[] images;                          // This must be a Byte[], not a byte[]
images = new Byte[imageResults.size()]; 
images = imageResults.toArray(images);  // arraycopy: element type mismatch

<br/>

It can however take a list of byte and put those into a Byte array:

byte myByte1 = 1;
byte myByte2 = 2;

List&lt;Byte&gt; imageResults = new ArrayList&lt;&gt;();
imageResults.add(myByte1);
imageResults.add(myByte2);

Byte[] images;                          // This must be a Byte[], not a byte[]
images = new Byte[imageResults.size()];
images = imageResults.toArray(images);

System.out.println(Arrays.toString(images));

// prints:
// [1, 2]

<br/>

It can also take an array of byte and put those into a two dimensional Byte array. Note that they are Byte arrays, not byte arrays though, since byte[] cannot be converted to Byte[]:

Byte[] myBytes1 = {0,1,2,3,4};
Byte[] myBytes2 = {5,6,7,8,9};

List&lt;Byte[]&gt; imageResults = new ArrayList&lt;&gt;();
imageResults.add(myBytes1);
imageResults.add(myBytes2);

Byte[][] images;
images = new Byte[imageResults.size()][];
images = imageResults.toArray(images);

System.out.println(Arrays.deepToString(images));

// prints:
// [[0, 1, 2, 3, 4], [5, 6, 7, 8, 9]]

<br/>

If you need a byte[][] and not a Byte[][], you can't use the toArray() method. Loop the ArrayList instead:

byte[] myBytes1 = {0,1,2,3,4};
byte[] myBytes2 = {5,6,7,8,9};

List&lt;byte[]&gt; imageResults = new ArrayList&lt;&gt;();
imageResults.add(myBytes1);
imageResults.add(myBytes2);

byte[][] images = new byte[imageResults.size()][];
for (int i = 0; i &lt; imageResults.size(); i++){
  images[i] = imageResults.get(i);
}

// alternative to the loop:
// IntStream.range(0, imageResults.size()).forEach(i -&gt; images[i] = imageResults.get(i));

System.out.println(Arrays.deepToString(images));

// prints:
// [[0, 1, 2, 3, 4], [5, 6, 7, 8, 9]]

huangapple
  • 本文由 发表于 2020年8月11日 18:33:51
  • 转载请务必保留本文链接:https://go.coder-hub.com/63356367.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定