Alibaba Cloud file upload display

1. The code uploads the image successfully, and the browser directly accesses the download problem:

(1) Use the third-level domain name;

(2) Specify the Content-Type of the uploaded file (the version of the OSS jar package may be inconsistent, please check the number):

 

ObjectMetadata objectMeta = new ObjectMetadata();
objectMeta.setContentType("image/jpg");//Mark the file type in metadata
objectMeta.setContentLength(out.toByteArray().length);

If it is set in Alibaba Cloud, right-click the file to set the HTTP header:

 



2. About the display of image upload:

Image path+?x-oss-process=image/resize,m_fill,h_100,w_100 //You can specify images to access compressed size

Image path+?x-oss-process=image/quality,q_20 //Image accessed by pixel compression

The above can be used for compressed uploaded images that need to be further adjusted when displayed in the app.

However, Alibaba Cloud Documentation does not provide the function of compressing and uploading, and only does a lot of rich processing for image display on the cloud.

 

3. Image upload and compression (refer to some uploads, which can be used)

The first time I used Thumbnailator, but I don't know why no matter how to modify the outputQuality ( 0.25f ) value, although it is compressed, the effect of setting 0.2 and 0.3 has no difference and the size has not changed. I haven't tried compressing the size, and if this doesn't work, I won't try again.

 

(1) The original size remains unchanged and the resolution is reduced (it is not recommended for large pictures, because it is unbearable to look directly at the mobile phone, I tried 5M, although the compression can be, but the distortion is serious, the following method is not suitable for png pictures, need Convert, there is no solution for now

https://stackoverflow.com/questions/15318677/how-do-i-write-a-bufferedimage-as-a-png-with-no-compression )

public class Test {
public static void main(String[] args) throws IOException {
       String endpoint = "";
       String accessKeyId = "";
       String accessKeySecret = "";
       String bucketName = "";//Actual
       //key
       String key = "images/23_iso100_14mm6.jpg";
       InputStream fileStream = new FileInputStream("D:/23_iso100_14mm.jpg");
       ByteArrayOutputStream swapStream = new ByteArrayOutputStream();
       byte[] buff = new byte[10485760]; //temporary upper limit 10M
       int rc = 0;
       while ((rc = fileStream.read(buff, 0, 10485760)) > 0) {
           swapStream.write(buff, 0, rc);
       }
      
       byte[] tempByte = compressPicByQuality(swapStream.toByteArray(), 0.2f);
       InputStream sbs = new ByteArrayInputStream(tempByte);
       OSSClient ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);
       ObjectMetadata objectMeta = new ObjectMetadata();
       objectMeta.setContentType("image/jpg");//Mark the file type in metadata
       objectMeta.setContentLength(tempByte.length);
       ossClient.putObject(bucketName, key, sbs,objectMeta);
       
   }
   
    /**
     * @Title: compressPicByQuality @Description: Compress the picture, keep the original size by compressing the picture quality @param quality: 0-1 @return byte[] @throws
     */
    public static byte[] compressPicByQuality(byte[] imgByte, float quality) {
        byte [] inByte = null;
        try {
            ByteArrayInputStream byteInput = new ByteArrayInputStream(imgByte);
            BufferedImage image = ImageIO.read(byteInput);

            // if the image is empty, return empty
            if (image == null) {
                return null;
            }
            // Get the writer of the specified Format image
            Iterator<ImageWriter> iter = ImageIO.getImageWritersByFormatName("jpg");// Get the iterator, jpg, jpeg
            ImageWriter writer = (ImageWriter) iter.next(); // 得到writer

            // Get the output parameter settings of the specified writer (ImageWriteParam)
            // ImageWriteParam iwp = writer.getDefaultWriteParam ();
            ImageWriteParam iwp = new JPEGImageWriteParam (null);
            // ImageWriteParam iwp = new P
            iwp.setCompressionMode(ImageWriteParam.MODE_EXPLICIT); // Set whether to compress
            iwp.setCompressionQuality(quality); // set compression quality parameters

            iwp.setProgressiveMode(ImageWriteParam.MODE_DISABLED);

            ColorModel colorModel = ColorModel.getRGBdefault();
            // Specify the color mode to use when compressing
            iwp.setDestinationType (
                    new javax.imageio.ImageTypeSpecifier(colorModel, colorModel.createCompatibleSampleModel(16, 16)));

            // Start to pack the image and write to byte[]
            ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); // Get memory output stream
            IIOImage iIamge = new IIOImage(image, null, null);

            // Here because the output requirement used to receive write information in ImageWriter must be ImageOutput
            // Through the static method in ImageIo, get the ImageOutput of byteArrayOutputStream
            writer.setOutput(ImageIO.createImageOutputStream(byteArrayOutputStream));
            writer.write(null, iIamge, iwp);
            inByte = byteArrayOutputStream.toByteArray();
        } catch (IOException e) {
            System.out.println("write errro");
            e.printStackTrace ();
        }
        return inByte;
    }
}

 

(2) Change the size and compress (better, temporarily used, but for png images, compression is difficult, there are special foreign paid software, do not consider it for the time being, there will be a comparison between jpg and png after compression, the clarity is ok )

public class Test {
public static void main(String[] args) throws IOException {
       String endpoint = "";
       String accessKeyId = "";
       String accessKeySecret = "";
       String bucketName = "";
       //key
       String key = "23_iso100_14mm6.jpg";
       InputStream fileStream = new FileInputStream("D:/23_iso100_14mm.jpg");
       ByteArrayOutputStream swapStream = new ByteArrayOutputStream();
       byte[] buff = new byte[10485760]; //temporary upper limit 10M
       int rc = 0;
       while ((rc = fileStream.read(buff, 0, 10485760)) > 0) {
           swapStream.write(buff, 0, rc);
       }
       ByteArrayInputStream in = new ByteArrayInputStream(swapStream.toByteArray()); //Use b as the input stream;
       BufferedImage image = ImageIO.read(in);  
       //1500 1500 jpg 268kb png 2.27M
       //1000 1000 jpg 125kb png 1.27M (still relatively large)
       ArrayList<Integer> arrayList = getAutoWidthAndHeight(image,1000,1000);
       int w = arrayList.get(0);
       int h = arrayList.get(1);
       Image newImage = image.getScaledInstance(w, h,Image.SCALE_DEFAULT);
       BufferedImage outputImage = new BufferedImage(w, h,BufferedImage.TYPE_INT_RGB);
       Graphics2D g = outputImage.createGraphics();
       g.drawImage(newImage, 0, 0, null); // draw the reduced image
       g.dispose();
       ByteArrayOutputStream out = new ByteArrayOutputStream();
       ImageIO.write(outputImage,"jpg",out);
       InputStream sbs = new ByteArrayInputStream(out.toByteArray());
       OSSClient ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);
       ObjectMetadata objectMeta = new ObjectMetadata();
       objectMeta.setContentType("image/jpg");//Mark the file type in metadata
       objectMeta.setContentLength(out.toByteArray().length);
       ossClient.putObject(bucketName, key, sbs,objectMeta);      
   }
  
   	/***
	   *
	   * @param bufferedImage image object to be scaled
	   * @param width_scale the width to scale to
	   * @param height_scale height to scale to
	   * @return a collection, the first element is the width, the second element is the height
	   */
	  public ArrayList<Integer> getAutoWidthAndHeight(BufferedImage bufferedImage,int width_scale,int height_scale){
	    ArrayList<Integer> arrayList = new ArrayList<Integer>();
	    int width = bufferedImage.getWidth();
	    int height = bufferedImage.getHeight();
	    if(width<=1000&&height<=1000){//The limit is not compressed (the simple version..)
	        arrayList.add(width);
            arrayList.add(height);
	    }else{
	        double scale_w =getDot2Decimal( width_scale,width);
	        System.out.println("getAutoWidthAndHeight width="+width + "scale_w="+scale_w);
	        double scale_h = getDot2Decimal(height_scale,height);
	        if (scale_w<scale_h) {
	          arrayList.add(parseDoubleToInt(scale_w*width));
	          arrayList.add(parseDoubleToInt(scale_w*height));
	        }
	        else {
	          arrayList.add(parseDoubleToInt(scale_h*width));
	          arrayList.add(parseDoubleToInt(scale_h*height));
	        }
	    }
	    return arrayList;
	      
	  }

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326035241&siteId=291194637