


Java obtains the remote network image file stream, compresses it and saves it locally
Nov 21, 2016 am 11:14 AMjava gets the image file stream from the remote network, compresses it and saves it locally
1. Get the image from the remote network
/** * 根據(jù)地址獲得數(shù)據(jù)的字節(jié)流 * * @param strUrl * 網(wǎng)絡(luò)連接地址 * @return */ public static byte[] getImageFromNetByUrl(String strUrl) { try { URL url = new URL(strUrl); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("GET"); conn.setConnectTimeout(5 * 1000); InputStream inStream = conn.getInputStream();// 通過輸入流獲取圖片數(shù)據(jù) byte[] btImg = readInputStream(inStream);// 得到圖片的二進制數(shù)據(jù) return btImg; } catch (Exception e) { e.printStackTrace(); } return null; }
/** * 根據(jù)地址獲得數(shù)據(jù)的字節(jié)流 * * @param strUrl * 本地連接地址 * @return */ public static byte[] getImageFromLocalByUrl(String strUrl) { try { File imageFile = new File(strUrl); InputStream inStream = new FileInputStream(imageFile); byte[] btImg = readInputStream(inStream);// 得到圖片的二進制數(shù)據(jù) return btImg; } catch (Exception e) { e.printStackTrace(); } return null; }
/** * 從輸入流中獲取數(shù)據(jù) * * @param inStream * 輸入流 * @return * @throws Exception */ public static byte[] readInputStream(InputStream inStream) throws Exception { ByteArrayOutputStream outStream = new ByteArrayOutputStream(); byte[] buffer = new byte[10240]; int len = 0; while ((len = inStream.read(buffer)) != -1) { outStream.write(buffer, 0, len); } inStream.close(); return outStream.toByteArray(); }
2. Convert the file read from the network into a local file
byte[] btImg1 = ImageUtil.getImageFromNetByUrl(fileUrl1); if (null != btImg1 && btImg1.length > 0) { logger.debug("讀取到:" + btImg1.length + " 字節(jié)"); ImageUtil.writeImageToDisk(btImg1, fileZipUrl1); } else { logger.debug("沒有從該連接獲得內(nèi)容"); } byte[] btImg2 = ImageUtil.getImageFromNetByUrl(fileUrl2); if (null != btImg2 && btImg2.length > 0) { logger.debug("讀取到:" + btImg2.length + " 字節(jié)"); ImageUtil.writeImageToDisk(btImg2, fileZipUrl2); } else { logger.debug("沒有從該連接獲得內(nèi)容"); }
/** * 將圖片寫入到磁盤 * * @param img * 圖片數(shù)據(jù)流 * @param fileName * 文件保存時的名稱 */ public static void writeImageToDisk(byte[] img, String zipImageUrl) { try { File file = new File(zipImageUrl); FileOutputStream fops = new FileOutputStream(file); fops.write(img); fops.flush(); fops.close(); System.out.println("圖片已經(jīng)寫入"+zipImageUrl); } catch (Exception e) { e.printStackTrace(); } }
3. Compress the local image
import java.io.*; import java.util.Date; import java.awt.*; import java.awt.image.*; import javax.imageio.ImageIO; import com.sun.image.codec.jpeg.*; /** * 圖片壓縮處理 */ public class ImgCompress { private Image img; private int width; private int height; /** * 構(gòu)造函數(shù) */ public ImgCompress(String fileName) throws IOException { File file = new File(fileName);// 讀入文件 img = ImageIO.read(file); // 構(gòu)造Image對象 width = img.getWidth(null); // 得到源圖寬 height = img.getHeight(null); // 得到源圖長 } /** * 按照寬度還是高度進行壓縮 * @param w int 最大寬度 * @param h int 最大高度 */ public void resizeFix(int w, int h) throws IOException { if (width / height > w / h) { resizeByWidth(w); } else { resizeByHeight(h); } } /** * 以寬度為基準,等比例放縮圖片 * @param w int 新寬度 */ public void resizeByWidth(int w) throws IOException { int h = (int) (height * w / width); resize(w, h); } /** * 以高度為基準,等比例縮放圖片 * @param h int 新高度 */ public void resizeByHeight(int h) throws IOException { int w = (int) (width * h / height); resize(w, h); } /** * 強制壓縮/放大圖片到固定的大小 * @param w int 新寬度 * @param h int 新高度 */ public void resize(int w, int h) throws IOException { // SCALE_SMOOTH 的縮略算法 生成縮略圖片的平滑度的 優(yōu)先級比速度高 生成的圖片質(zhì)量比較好 但速度慢 BufferedImage image = new BufferedImage(w, h,BufferedImage.TYPE_INT_RGB ); image.getGraphics().drawImage(img, 0, 0, w, h, null); // 繪制縮小后的圖 File destFile = new File("C:/Users/Administrator/Desktop/147.jpg"); FileOutputStream out = new FileOutputStream(destFile); // 輸出到文件流 // 可以正常實現(xiàn)bmp、png、gif轉(zhuǎn)jpg JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out); encoder.encode(image); // JPEG編碼 out.close(); }
@SuppressWarnings("deprecation") public static void main(String[] args) throws Exception { System.out.println("開始:" + new Date().toLocaleString()); ImgCompress imgCom = new ImgCompress("C:/Users/Administrator/Desktop/1479209533362.jpg"); imgCom.resizeFix(285, 380); System.out.println("結(jié)束:" + new Date().toLocaleString()); }
}
End ~

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

To correctly handle JDBC transactions, you must first turn off the automatic commit mode, then perform multiple operations, and finally commit or rollback according to the results; 1. Call conn.setAutoCommit(false) to start the transaction; 2. Execute multiple SQL operations, such as INSERT and UPDATE; 3. Call conn.commit() if all operations are successful, and call conn.rollback() if an exception occurs to ensure data consistency; at the same time, try-with-resources should be used to manage resources, properly handle exceptions and close connections to avoid connection leakage; in addition, it is recommended to use connection pools and set save points to achieve partial rollback, and keep transactions as short as possible to improve performance.

TheJVMenablesJava’s"writeonce,runanywhere"capabilitybyexecutingbytecodethroughfourmaincomponents:1.TheClassLoaderSubsystemloads,links,andinitializes.classfilesusingbootstrap,extension,andapplicationclassloaders,ensuringsecureandlazyclassloa

Use classes in the java.time package to replace the old Date and Calendar classes; 2. Get the current date and time through LocalDate, LocalDateTime and LocalTime; 3. Create a specific date and time using the of() method; 4. Use the plus/minus method to immutably increase and decrease the time; 5. Use ZonedDateTime and ZoneId to process the time zone; 6. Format and parse date strings through DateTimeFormatter; 7. Use Instant to be compatible with the old date types when necessary; date processing in modern Java should give priority to using java.timeAPI, which provides clear, immutable and linear

Pre-formanceTartuptimeMoryusage, Quarkusandmicronautleadduetocompile-Timeprocessingandgraalvsupport, Withquarkusoftenperforminglightbetterine ServerLess scenarios.2.Thyvelopecosyste,

Networkportsandfirewallsworktogethertoenablecommunicationwhileensuringsecurity.1.Networkportsarevirtualendpointsnumbered0–65535,withwell-knownportslike80(HTTP),443(HTTPS),22(SSH),and25(SMTP)identifyingspecificservices.2.PortsoperateoverTCP(reliable,c

Java's garbage collection (GC) is a mechanism that automatically manages memory, which reduces the risk of memory leakage by reclaiming unreachable objects. 1.GC judges the accessibility of the object from the root object (such as stack variables, active threads, static fields, etc.), and unreachable objects are marked as garbage. 2. Based on the mark-clearing algorithm, mark all reachable objects and clear unmarked objects. 3. Adopt a generational collection strategy: the new generation (Eden, S0, S1) frequently executes MinorGC; the elderly performs less but takes longer to perform MajorGC; Metaspace stores class metadata. 4. JVM provides a variety of GC devices: SerialGC is suitable for small applications; ParallelGC improves throughput; CMS reduces

defer is used to perform specified operations before the function returns, such as cleaning resources; parameters are evaluated immediately when defer, and the functions are executed in the order of last-in-first-out (LIFO); 1. Multiple defers are executed in reverse order of declarations; 2. Commonly used for secure cleaning such as file closing; 3. The named return value can be modified; 4. It will be executed even if panic occurs, suitable for recovery; 5. Avoid abuse of defer in loops to prevent resource leakage; correct use can improve code security and readability.

Gradleisthebetterchoiceformostnewprojectsduetoitssuperiorflexibility,performance,andmoderntoolingsupport.1.Gradle’sGroovy/KotlinDSLismoreconciseandexpressivethanMaven’sverboseXML.2.GradleoutperformsMaveninbuildspeedwithincrementalcompilation,buildcac
