標籤:cms coder tostring encoder gif [] 存在 str private
說明:之所以要轉換為BASE64是因為我這個涉及到跨系統圖片的傳輸。將file傳輸到另外一個系統,另外一個系統再進行檔案上傳。
這之間,從A到B的過程,圖片是存在xml中的某個節點中的。到了B系統要進行xml轉map的過程。所以在這個過程中,無法從map中取出byte[]或File類型的檔案。因為轉換過後map取出來的value值無法強轉為byte[]或File,所以只能轉換為BASE64字串傳值。到了B端再轉為byte[]進行檔案上傳操作
public class FileStreamUtil {
private static String folderUrl;
static BASE64Encoder encoder = new sun.misc.BASE64Encoder();
static BASE64Decoder decoder = new sun.misc.BASE64Decoder();
//將圖片以二進位流
public static String fileToBase64(File file) throws IOException
{
BufferedImage bi;
bi = ImageIO.read(file);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ImageIO.write(bi, "jpg", baos);
byte[] bytes = baos.toByteArray();
return encoder.encodeBuffer(bytes).trim();
}
/**
* 將二進位轉換為byte[]
* @param base64String
*/
public static byte[] base64StringToImage(String base64String){
byte[] bytes = new byte[base64String.length()];
try {
bytes = decoder.decodeBuffer(base64String);
return bytes;
} catch (IOException e) {
e.printStackTrace();
}
return bytes;
}
//將file檔案轉換為byte[]
public static byte[] fileToByte(File file) throws IOException
{
BufferedImage bi;
bi = ImageIO.read(file);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ImageIO.write(bi, "jpg", baos);
byte[] bytes = baos.toByteArray();
return bytes;
}
/**
* 將file寫入到目標源:該方法暫時不用
* @param File
*/
public static void writeFile(File file){
try {
byte[] bytes=fileToByte(file);
ByteArrayInputStream bais = new ByteArrayInputStream(bytes);
BufferedImage bi1 =ImageIO.read(bais); //讀取源檔案
ImageIO.write(bi1, "jpg", file);//不管輸出什麼格式圖片,此處不需改動
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* 檔案上傳到伺服器
* @param bytes
*/
public static void wireteByte(byte[] bytes){
String toUrl="";//目標地址
File w2 = new File(toUrl);//可以是jpg,png,gif格式 "d://base64String.jpg"
try {
ByteArrayInputStream bais = new ByteArrayInputStream(bytes);
BufferedImage bi1 =ImageIO.read(bais); //讀取源檔案
ImageIO.write(bi1, "jpg", w2);//不管輸出什麼格式圖片,此處不需改動
} catch (IOException e) {
LoggerUtil.trace("FileStreamUtil-----","wireteByte---", "上傳傳輸伺服器系統出錯");
e.printStackTrace();
}
}
/**
* 產生uuid
* 擷取fileId
* @return
*/
@SuppressWarnings("unused")
public static String getFileId() {
UUID uuid = UUID.randomUUID();
String fileid = StringUtils.replace(uuid.toString(), "-", "");
return fileid;
}
/**
* 設定nas路徑
* @param fileId
* @param uploadFile
* @return
*/
@SuppressWarnings("unused")
public static String getFilePath(String fileId){
String fileType = ".jpg";
String fileName = fileId + fileType;
String dateString = DateFormatUtil.formatDate(new Date(), "yyyyMMdd");
String fileNasPath = folderUrl + "/scms/" + dateString + "/" + fileName;
return fileNasPath;
}
}
圖片上傳相關