ios圖片上傳翻轉問題解決

 

開發微信服務,有個上傳頭像的功能,前端用html5的方法來上傳頭像html

<img id="babyHead" src="$session.getAttribute('picUrl')" style="width:74px;height:74px;border-radius:37px;"/>
<label class="camera"><i class="fa fa-camera" aria-hidden="true"></i>
<input id="f1" name="f1" class="weui_uploader_input" type="file" capture="camera" accept="image/*" multiple="">
.on("change", "#f1", function () {
		$("#loadingToast").show()
        var fileName = $(this).val();
        if (fileName.length > -1) {
        	jQuery.ajaxFileUpload({
  			  url:jQuery("#confirmUrl").val(),
  			  type: 'post',
  			  secureuri:false,
  			  fileElementId:'f1',
  			  data:{
  			  type:'5'},
  			  dataType:"json",
  			  success: function(data, status){ 
  				  $('#babyHead').attr('src',data.url);
  				$('#headUrl').val(data.url);
  				$("#loadingToast").hide();
              },error:function(data,status,e){
  				alert(e);
  			}
  		});
        } else {
            alert("請選擇圖片上傳!");
        }
    });

上傳到後端的頭像居然會出現各類翻轉,基本就是90度的倍數。前端

查找後得知是ios的拍照片時記錄了拍攝的翻轉角度。爲了把這個角度糾正過來,在java中須要調用metadata-extractorhtml5

maven引用以下java

<dependency>
		<groupId>com.drewnoakes</groupId>
		<artifactId>metadata-extractor</artifactId>
		<version>2.9.1</version>
	</dependency>

網上不少引用2.3.1的作法,實際上已經不能用了,在2.9.1中原先老的ExifDirector變成了n個directory,我經過for循環挨個試出來,當ExifDirector爲ExifIFD0Directory時,才能夠調用ExifDirectoryBase.TAG_ORIENTATION來判斷翻轉的角度,具體方法以下面的代碼,個人思路是獲得翻轉的數值:6,3,8來獲得須要右轉的角度:90,180,270,而後調用Graphics2D的rotate方法來翻轉ios

1.獲得角度ajax

private int getRotateAngleForPhoto(String filePath) {
		int angle = 0;
		File imgFile = new File(filePath);
		try {
			Metadata metadata = ImageMetadataReader.readMetadata(imgFile);
			for (Directory directory : metadata.getDirectories()) {
				if ("ExifIFD0Directory".equalsIgnoreCase(directory.getClass()
						.getSimpleName())) {
					if (directory
							.containsTag(ExifDirectoryBase.TAG_ORIENTATION)) {
						// Exif信息中方向  
						int orientation = directory
								.getInt(ExifDirectoryBase.TAG_ORIENTATION);
						logger.info("orientation=" + orientation);
						switch (orientation) {
						case 6:
							angle = 90;
							break;
						case 3:
							angle = 180;
							break;
						case 8:
							angle = 270;
							break;
						default:
							return 0;
						}

					}
				}

			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return angle;
	}

2.調用的翻轉方法apache

import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.Transparency;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

import javax.imageio.ImageIO;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
/**
	 * 向右旋轉angle角度
	 * @param img
	 * @param angle
	 * @return
	 */
	public static void rotate(File image, int angle,String targetFolderPath,String targetFileName) throws IOException {
		BufferedImage img = ImageIO.read(image);
		int w = img.getWidth();
		int h = img.getHeight();
		BufferedImage dimg = new BufferedImage(w, h, img.getType());
		Graphics2D g = dimg.createGraphics();
		g.rotate(Math.toRadians(angle), w / 2, h / 2);
		g.drawImage(img, null, 0, 0);
		commonIoWrite(targetFolderPath, targetFileName, dimg, g);
	}

 

3.根據翻轉的角度來調用對應的rotate方法json

int angle = getRotateAngleForPhoto(sourcePath);
if (getRotateAngleForPhoto(sourcePath) > 0) {
	ImageUtil.rotate(new File(smallPath),angle, path, smallFileName);
}

其中smallPath是源文件地址,angle是向右翻轉角度,path是目標文件夾,smallFileName是最終的文件名
                        後端

相關文章
相關標籤/搜索