好得很程序员自学网

<tfoot draggable='sEl'></tfoot>

java实现上传图片尺寸修改和质量压缩

本文实例为大家分享了java实现上传图片尺寸修改和质量压缩的具体代码,供大家参考,具体内容如下

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

71

72

73

74

75

76

77

78

79

80

81

82

83

84

85

86

87

88

89

90

91

92

93

94

95

96

97

98

99

100

101

102

103

104

105

106

107

108

109

110

111

112

113

114

115

116

117

118

119

120

121

122

123

124

125

126

127

128

129

130

131

132

133

134

135

136

137

138

139

140

141

142

143

144

145

146

147

148

149

150

151

152

153

154

155

156

157

158

159

160

161

162

163

164

165

166

167

168

169

170

171

172

173

174

175

176

177

178

179

180

181

182

183

184

185

186

187

188

189

190

191

192

193

194

195

196

197

198

199

200

201

202

203

204

205

206

207

208

209

210

211

212

213

214

215

216

217

218

219

220

221

222

223

224

225

226

227

228

229

230

231

232

233

234

235

236

237

238

239

240

241

242

243

244

245

246

247

248

249

250

251

252

253

254

255

256

257

258

259

260

261

262

263

264

265

266

267

268

269

270

271

272

273

274

275

276

277

278

279

280

281

282

283

284

285

286

287

288

289

290

291

292

293

294

295

296

297

298

299

300

301

302

303

304

305

306

307

308

309

310

311

312

313

314

315

316

317

318

319

320

321

322

323

324

325

326

327

328

329

330

331

332

333

334

335

336

337

338

339

340

341

342

343

344

345

346

347

348

349

350

351

352

package com.zity.frame.util;

 

/**  

  *  缩略图实现,将图片(jpg、bmp、png、gif等等)真实的变成想要的大小  

  */

 

import com.sun.image.codec.jpeg.JPEGCodec;

import com.sun.image.codec.jpeg.JPEGImageEncoder;

import net.sourceforge.pinyin4j.PinyinHelper;

 

import javax.imageio.ImageIO;

import java.awt.*;

import java.awt.image.BufferedImage;

import java.io.*;

import java.net.MalformedURLException;

import java.net.URL;

import java.net.URLConnection;

import java.util.Random;

  

/*******************************************************************************  

  * 缩略图类(通用) 本java类能将jpg、bmp、png、gif图片文件,进行等比或非等比的大小转换。 具体使用方法  

  * compressPic(大图片路径,生成小图片路径,大图片文件名,生成小图片文名,生成小图片宽度,生成小图片高度,是否等比缩放(默认为true))  

  */

  public class CompressPic {

      private File file = null ; // 文件对象

      private String inputDir; // 输入图路径

      private String outputDir; // 输出图路径

      private String inputFileName; // 输入图文件名

      private String outputFileName; // 输出图文件名

      private int outputWidth = 300 ; // 默认输出图片宽

      private int outputHeight = 150 ; // 默认输出图片高

      private boolean proportion = true ; // 是否等比缩放标记(默认为等比缩放)

      public CompressPic() { // 初始化变量

          inputDir = "" ;    

          outputDir = "" ;    

          inputFileName = "" ;    

          outputFileName = "" ;    

          outputWidth = 300 ;    

          outputHeight = 150 ;    

      }    

      public void setInputDir(String inputDir) {    

          this .inputDir = inputDir;    

      }    

      public void setOutputDir(String outputDir) {    

          this .outputDir = outputDir;    

      }    

      public void setInputFileName(String inputFileName) {    

          this .inputFileName = inputFileName;   

      }    

      public void setOutputFileName(String outputFileName) {    

          this .outputFileName = outputFileName;    

      }    

      public void setOutputWidth( int outputWidth) {   

          this .outputWidth = outputWidth;    

      }    

      public void setOutputHeight( int outputHeight) {    

          this .outputHeight = outputHeight;    

      }    

      public void setWidthAndHeight( int width, int height) {    

          this .outputWidth = width;   

          this .outputHeight = height;    

      }    

        

      /*   

      * 获得图片大小   

      * 传入参数 String path :图片路径   

      */    

      public long getPicSize(String path) {    

          file = new File(path);

          return file.length();

      }   

        

      /**

      * 图片处理

      * @return

      */

      public String compressPic() {    

          try {    

              //获得源文件    

              file = new File(inputDir + inputFileName);    

              if (!file.exists()) {    

                  return "" ;    

              }

              // 生成存储路径

              File outDir = new File(outputDir);

              if (!outDir.exists()){

                 outDir.mkdirs();

              }

              Image img = ImageIO.read(file);

              // 判断图片格式是否正确    

              if (img== null ){

                 return "" ;

              }

              if (img.getWidth( null ) == - 1 ) {   

                  System.out.println( " can't read,retry!" + "<BR>" );    

                  return "no" ;    

              } else {    

                  int newWidth; int newHeight;    

                  // 判断是否是等比缩放    

                  if ( this .proportion == true ) {    

                      // 为等比缩放计算输出的图片宽度及高度    

                     int w =img.getWidth( null );

                     int h = img.getHeight( null );

                     //如果图片的宽度小于等于250,并且高度小于等于183,图片原样输出

                     if (w<= 300 ){

                         outputWidth=w;

                     }

                     if (h<= 150 ){

                         outputHeight=h;

                     }

                      double rate1 = (( double ) img.getWidth( null )) / ( double ) outputWidth;    

                      double rate2 = (( double ) img.getHeight( null )) / ( double ) outputHeight;    

                      // 根据缩放比率大的进行缩放控制    

//                     double rate = rate1 > rate2 ? rate1 : rate2;

                      // 保证宽度为250px

                      double rate = rate1;

                      newWidth = ( int ) ((( double ) img.getWidth( null )) / rate);    

                      newHeight = ( int ) ((( double ) img.getHeight( null )) / rate2);    

                  } else {    

                      newWidth = outputWidth; // 输出的图片宽度    

                      newHeight = outputHeight; // 输出的图片高度    

                  }

                 

                  //重新设置高宽为图片真实高宽,上面的高宽是其他项目需要300*150的,我没得空删掉

                 newWidth = getImgWidth(file);

                 newHeight = getImgHeight(file);

                BufferedImage tag = new BufferedImage(( int ) newWidth, ( int ) newHeight, BufferedImage.TYPE_INT_RGB);

                   

                /*  

                  * Image.SCALE_SMOOTH 的缩略算法 生成缩略图片的平滑度的  

                  * 优先级比速度高 生成的图片质量比较好 但速度慢  

                  */    

                tag.getGraphics().drawImage(img.getScaledInstance(newWidth, newHeight, Image.SCALE_SMOOTH), 0 , 0 , null );   

                FileOutputStream out = new FileOutputStream(outputDir + outputFileName);   

                // JPEGImageEncoder可适用于其他图片类型的转换    

                JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);    

                encoder.encode(tag);    

                out.close();    

              }    

          } catch (IOException ex) {    

              ex.printStackTrace();    

          }    

          return "ok" ;    

    }

    

    /**

      * 图片处理入口

      * @param inputDir 输入图路径

      * @param outputDir 输出图路径

      * @param inputFileName 输入图名

      * @param outputFileName 输出图名

      * @return

      */

    public String compressPic (String inputDir, String outputDir, String inputFileName, String outputFileName) {    

        // 输入图路径    

        this .inputDir = inputDir;    

        // 输出图路径    

        this .outputDir = outputDir;    

        // 输入图文件名    

        this .inputFileName = inputFileName;    

        // 输出图文件名   

        this .outputFileName = outputFileName;    

        return compressPic();    

    }    

    

    /**

      * 图片处理入口

      * @param inputDir 输入图路径

      * @param outputDir 输出图路径

      * @param inputFileName 输入图名

      * @param outputFileName 输出图名

      * @param width 输出图宽度

      * @param height 输入图宽度

      * @param gp 等比缩放

      * @return

      */

    public String compressPic(String inputDir, String outputDir, String inputFileName, String outputFileName, int width, int height, boolean gp) {    

        // 输入图路径    

        this .inputDir = inputDir;    

        // 输出图路径    

        this .outputDir = outputDir;    

        // 输入图文件名    

        this .inputFileName = inputFileName;    

        // 输出图文件名    

        this .outputFileName = outputFileName;    

        // 设置图片长宽   

        setWidthAndHeight(width, height);    

        // 是否是等比缩放 标记    

        this .proportion = gp;    

        return compressPic();    

    }

    

    /**

      * 图片压缩

      * @param downloadUrl

      * @param inputDir

      * @param outDir

      * @return

      */

    public String ImageCompression(String downloadUrl,String inputDir,String outDir){

        

         Random rnd = new Random();

         String picName = downloadUrl.substring(downloadUrl.lastIndexOf( "/" )+ 1 );

         String extendName = "" ;

         String beforeName= "" ;

        

         if (picName.contains( "." )){

             extendName = picName.substring(picName.indexOf( "." ));

             beforeName= picName.substring( 0 ,picName.indexOf( "." ));

         } else {

             extendName = picName;

             beforeName= picName;

         }

        

         //随机数

         Integer r = rnd.nextInt( 1000 );

         beforeName = new CompressPic().getPinYinHeadChar(beforeName);

         long ts = System.currentTimeMillis();

         String outpicName=ts+beforeName+r+ ".jpg" ;

         outpicName = outpicName.replace( "%" , "" );

         if (outpicName.contains( "张栋杰总经理会见旭阳集团董事长杨雪岗" )){

             outpicName= "zdjzjlhjxyjtdszyxg.jpg" ;

         }

        

         if (httpDownload(downloadUrl, inputDir, outpicName)){

             // 当前时间

            // String curTime = new Long(System.currentTimeMillis()).toString();

            this .compressPic(inputDir, outDir, outpicName, outpicName, 300 , 150 , true );

            return outpicName;

        } else {

             return null ;

         }

    }

    

    /**

      * http图片下载

      * @param httpUrl

      * @param saveFile

      * @return

      */

    public static boolean httpDownload(String httpUrl,String saveDir,String saveName){

         // 下载网络文件

         int bytesum = 0 ;

         int byteread = 0 ;

         URL url = null ;  

        try {

            url = new URL(httpUrl);  

        } catch (MalformedURLException e1) {  

            e1.printStackTrace();

            return false ;  

        }

        // 存储目录

        File outDir = new File(saveDir);

        if (!outDir.exists()){

             outDir.mkdirs();

        }

        try {

             URLConnection conn = url.openConnection();

             InputStream inStream = conn.getInputStream();

             FileOutputStream fs = new FileOutputStream(saveDir+saveName);

            

             byte [] buffer = new byte [ 1204 ];

             while ((byteread = inStream.read(buffer)) != - 1 ) {

                 bytesum += byteread;

                 fs.write(buffer, 0 , byteread);

             }

             fs.close();

             inStream.close();

        } catch (FileNotFoundException e) {

             e.printStackTrace();

             return false ;

        } catch (IOException e) {

             e.printStackTrace();

             return false ;

        }

        return true ;

    }

    /** 

      * 提取每个汉字的首字母 

      *  

      * @param str 

      * @return String 

      */

    public   String getPinYinHeadChar(String str) {  

        String convert = "" ;  

        for ( int j = 0 ; j < str.length(); j++) {  

            char word = str.charAt(j);  

            // 提取汉字的首字母  

            String[] pinyinArray = PinyinHelper.toHanyuPinyinStringArray(word);  

            if (pinyinArray != null ) {  

                convert += pinyinArray[ 0 ].charAt( 0 );  

            } else {  

                convert += word;  

            }  

        }  

        return convert;  

    }  

    public static void main(String[] arg) {

        CompressPic mypic = new CompressPic();

         mypic.compressPic( "C:\\Users\\mazhaoxu\\Desktop\\" , "C:\\Users\\mazhaoxu\\Desktop\\" , "微信图片_20180712182800.png" , "2019061818542824511111111111.png" );

//        if(httpDownload("http://221.195.72.44:8122/NR/rdonlyres/B5071DE7-9652-44AF-9534-0EE0ED2DCA92/15177/resource_651768621.jpg", "D:\\data\\resource_651768621.jpg")){

//            int start = (int) System.currentTimeMillis();   // 开始时间

//            mypic.compressPic("D:\\data\\", "D:\\data\\", "resource_651768621.jpg", "r1"+start+".jpg", 250, 250, true);

//        }

//       String s=  mypic.getPinYinHeadChar("http://114.251.186.42:81/web-s/images/1447069462915xfydh1_fb_fb521.jpg");

//        mypic.ImageCompression("http://114.251.186.42:81/web-s/images/mobile/1447069462915xfydh1_fb_fb521.jpg","d:\\images\\", "d:\\images\\mobile\\");

//        mypic.compressPic("d:\\", "d:\\image\\mobile", "144921941137520151204fgw1747.jpg", "144921941137520151204fgw1747.jpg");

//        String s = "/image/dslfsjss/image/sisis /image";

//            System.out.println(s.replace("/image/", "/mobile/image/"));

    }

 

 

     /**

     * 获取图片宽度

     * @param file  图片文件

     * @return 宽度

     */

     public static int getImgWidth(File file) {

         InputStream is = null ;

         BufferedImage src = null ;

         int ret = - 1 ;

         try {

             is = new FileInputStream(file);

             src = javax.imageio.ImageIO.read(is);

             ret = src.getWidth( null ); // 得到源图宽

             is.close();

         } catch (Exception e) {

             e.printStackTrace();

         }

         return ret;

     }

 

     /**

     * 获取图片高度

     * @param file  图片文件

     * @return 高度

     */

     public static int getImgHeight(File file) {

         InputStream is = null ;

         BufferedImage src = null ;

         int ret = - 1 ;

         try {

             is = new FileInputStream(file);

             src = javax.imageio.ImageIO.read(is);

             ret = src.getHeight( null ); // 得到源图高

             is.close();

         } catch (Exception e) {

             e.printStackTrace();

         }

         return ret;

     }

  }  

这是我用的工具类,其中里面业务会用到pinyin4j的jar包,和图片压缩关系不大,可以去除,我是因为比较着急改完,就没动,如果不想改,需要引入pinyin4j的jar包。

maven:

?

1

2

3

4

5

6

<!-- https://mvnrepository.com/artifact/com.belerweb/pinyin4j -->

         < dependency >

             < groupId >com.belerweb</ groupId >

             < artifactId >pinyin4j</ artifactId >

             < version >2.5.0</ version >

</ dependency >

可以自行用上面工具类里的main方法进行测试

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。

原文链接:https://blog.csdn.net/qq_37202864/article/details/93212010

查看更多关于java实现上传图片尺寸修改和质量压缩的详细内容...

  阅读:12次