图片处理

本文介绍了一种处理图片上传、复制、修改等操作的方法,并详细解释了如何将图片写入硬盘、从硬盘读取图片、处理图片重名等问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1. 把图片写入硬盘

// 获取线路code

code = util.getCircuitryCode(orgCode, po.getStartplace(),po.getTargetplace(), String.valueOf(po.getTraveldays()));

// 工程类路径,用来获取保存头像的路径

String url = request.getSession().getServletContext()

.getRealPath(request.getRequestURI());

int a = url.lastIndexOf(File.separator);

url = url.substring(0, a);

StringBuffer dirPath = new StringBuffer(url).append(

File.separator).append("picture");

filePath = fileItem.getName();

if (filePath != null && !"".equalsIgnoreCase(filePath)) {

// 创建文件夹

createdir[微软用户1](code, dirPath);

TAttachment ta = new TAttachment();

// 获取图片或文件的名字

fileName = filePath.substring(filePath.lastIndexOf("\\") + 1);

// 循环图片名字判断是否有重复的

for (int i = 0; i < pathnameList.size(); i++) {

String beforFileName = (String) pathnameList.get(i);

if (beforFileName.equals(fileName)) {

fileName = "little"+ i+ filePath.substring(filePath.lastIndexOf("\\") + 1);

}

}

dirPath.append("/");

outPath = dirPath.toString() + fileName;

// 写入文件

if (!"".equals(filePath)) {

ins = fileItem.getInputStream();

os = new FileOutputStream(outPath);

bytesRead = 0;

buffer = newbyte[4096];

while ((bytesRead = ins.read(buffer, 0, 4096)) != -1) {

os.write(buffer, 0, bytesRead);

}

buffer = null;

os.close();

ins.close();

}

fileSize = fileItem.getSize();

// 把图片名字添加到list中,以便判断是否有相同的图片名字

pathnameList.add(fileName);

extend1 = fileName.substring(fileName.lastIndexOf(".") + 1);

byte[] bytes = newbyte[12];

ta.setName(fileName);

ta.setContexts(bytes);

ta.setCreatetime(new Date());

ta.setCreatorid(creatorid);

ta.setCreatororgid(creatororgid);

ta.setCreatorip(ip);

ta.setExtend(extend1);

ta.setFilepath("/picture/circuitryPictrue/" + code

+ "/" + fileName);

2. 复制

code = util.getCircuitryCode(orgCode, po.getStartplace(),po.getTargetplace(), String.valueOf(po.getTraveldays()));

// 工程类路径,用来获取保存头像的路径

String url = request.getSession().getServletContext().getRealPath(request.getRequestURI());

int a = url.lastIndexOf(File.separator);

url = url.substring(0, a);

StringBuffer dirPaths = new StringBuffer(url);// 用来删除文件用的

StringBuffer dirPath = new StringBuffer(url).append(File.separator).append("picture");

String fileid = fileItem.getFieldName(); // 用来获取浏览文本框的ID

filePath = fileItem.getName();

// 获取图片或文件的名字

fileName = filePath.substring(filePath.lastIndexOf("\\") + 1);

if (fileid.equals("haveBigPic")) {

if (filePath == null || filePath.equals("")) {

type = "BIGPIC";

attachement = logic.getAttachment(relationId, type);

// 调用复制的方法

filePath = copyPicture[微软用户2](code, ip, filePath,creatororgid, creatorid, set_ta, tattBig,attachement, dirPaths, dirPath);

3. 修改TAttachment ta = null;

// 工程类路径,用来获取保存头像的路径

String url = request.getSession().getServletContext()

.getRealPath(request.getRequestURI());

int a = url.lastIndexOf(File.separator);

url = url.substring(0, a);

StringBuffer dirPath = new StringBuffer(url).append(

File.separator).append("picture");

StringBuffer dirPaths = new StringBuffer(url);// 此字符串用来删除文件夹的

String fileid = fileItem.getFieldName(); // 用来获取浏览文本框的ID

filePath = fileItem.getName();

if (filePath != null && !"".equalsIgnoreCase(filePath)) {

// 创建文件夹

createdir(code, dirPath);

fileName = filePath.substring(filePath

.lastIndexOf("\\") + 1);

// 调用处理图片同名的方法

fileName = picrename[微软用户3](code, filePath, fileName, po,

pathnameList, dirPaths, fileid);

dirPath.append("/");

outPath = dirPath.toString() + fileName;

// 写入文件说

if (!"".equals(filePath)) {

ins = fileItem.getInputStream();

os = new FileOutputStream(outPath);

bytesRead = 0;

buffer = newbyte[4096];

while ((bytesRead = ins.read(buffer, 0, 4096)) != -1) {

os.write(buffer, 0, bytesRead);

}

buffer = null;

os.close();

ins.close();

}

fileSize = fileItem.getSize();

pathnameList.add(fileName);// filename存入list,用来判断图片重名

extend1 = fileName

.substring(fileName.lastIndexOf(".") + 1);

byte[] bytes = newbyte[12];

Set ts = po.getTAttachments();

Iterator it = ts.iterator();

boolean flag = false;

if ("haveBigPic".equalsIgnoreCase(fileItem

.getFieldName())) {

while (it.hasNext()) {

ta = (TAttachment) it.next();

if (Constants.C_ATTACHMENT_TYPE_BIG

.equalsIgnoreCase(ta.getType())) {

flag = true;

break;

}

}

} elseif ("haveLittlePic".equalsIgnoreCase(fileItem

.getFieldName())) {

while (it.hasNext()) {

ta = (TAttachment) it.next();

if (Constants.C_ATTACHMENT_TYPE_SMALL.equalsIgnoreCase(ta.getType())) {

flag = true;

break;

}

}

} elseif ("haveWordFile".equalsIgnoreCase(fileItem

.getFieldName())) {

while (it.hasNext()) {

ta = (TAttachment) it.next();

if (Constants.C_ATTACHMENT_TYPE_DOC

.equalsIgnoreCase(ta.getType())) {

flag = true;

break;

}

}

}

if (flag) {

if (Constants.C_ATTACHMENT_TYPE_BIG

.equalsIgnoreCase(ta.getType())) {

if ("bmp".equalsIgnoreCase(extend1)

|| "gif".equalsIgnoreCase(extend1)

|| "jpg".equalsIgnoreCase(extend1)

|| "jpeg".equalsIgnoreCase(extend1)

|| "tiff".equalsIgnoreCase(extend1)

|| "psd".equalsIgnoreCase(extend1)

|| "png".equalsIgnoreCase(extend1)

|| "swf".equalsIgnoreCase(extend1)) {

ta.setKind(Constants.C_ATTACHMENT_KIND_PHO);

ta.setType(Constants.C_ATTACHMENT_TYPE_BIG);

} else {

thrownew BusinessException("请上传正确的格式图片");

}

} elseif (Constants.C_ATTACHMENT_TYPE_SMALL

.equalsIgnoreCase(ta.getType())) {

if ("jpg".equalsIgnoreCase(extend1)) {

ta.setKind(Constants.C_ATTACHMENT_KIND_PHO);

ta

.setType(Constants.C_ATTACHMENT_TYPE_SMALL);

} else {

thrownew BusinessException("请上传JPG格式图片");

}

} elseif (Constants.C_ATTACHMENT_TYPE_DOC

.equalsIgnoreCase(ta.getType())) {

if ("doc".equalsIgnoreCase(extend1)

|| "pdf".equalsIgnoreCase(extend1)

|| "xls".equalsIgnoreCase(extend1)) {

ta.setKind(Constants.C_ATTACHMENT_KIND_DOC);

ta.setType(Constants.C_ATTACHMENT_TYPE_DOC);

} else {

thrownew BusinessException(

"请上传WORD文档或PDF文件");

}

}

ta.setContexts(bytes);

ta.setName(fileName);

ta.setContexts(bytes);

ta.setCreatetime(new Date());

ta.setCreatorid(changerid);

ta.setCreatororgid(changerorgid);

ta.setCreatorip(ip);

ta.setExtend(extend1);

ta.setFilepath("/picture/circuitryPictrue/" + code

+ "/" + fileName);

ta.setFilesize(String.valueOf(fileSize));

set.add(ta);

3. 读取到界面

// 把图片读入页面

public ActionForward readpic(ActionMapping mapping, ActionForm form,

HttpServletRequest request, HttpServletResponse response)

throws Exception {

File uploadFile = null;

try {

String id = request.getParameter("id");

TAttachment t = (TAttachment) logic.getDao().getHibernateTemplate()

.get(TAttachment.class, id);

// 获取取数据库中的filepath路径

String bytes = t.getFilepath();

// 工程类路径,用来获取保存头像的路径

String url = request.getSession().getServletContext().getRealPath(

request.getRequestURI());

int a = url.lastIndexOf(File.separator);

url = url.substring(0, a);

BufferedInputStream bis = null;

BufferedOutputStream bos = null;

OutputStream fos = null;

InputStream fis = null;

String filepath = bytes;

uploadFile = new File(url + filepath);

fis = new FileInputStream(uploadFile);

bis = new BufferedInputStream(fis);

fos = response.getOutputStream();

bos = new BufferedOutputStream(fos);

// 这个就就是弹出下载对话框的关键代码

// response.setHeader("Content-disposition", "attachment;filename="

// + URLEncoder.encode(bytes, "utf-8"));

int bytesRead = 0;

// 用输入流进行先读,然后用输出流去写

byte[] buffer = newbyte[8192];

while ((bytesRead = bis.read(buffer, 0, 8192)) != -1) {

bos.write(buffer, 0, bytesRead);

}

bos.flush();

fis.close();

bis.close();

fos.close();

bos.close();

} catch (Exception ex) {

return mapping.findForward("error");

}

returnnull;

4. }

5下载附件,如wordpdf等等

public ActionForward download(ActionMapping mapping, ActionForm form,

HttpServletRequest request, HttpServletResponse response)

throws Exception {

byte[] buffer;

InputStream ins;

String id = "", dirPaths, filepath;

try {

// 工程类路径,用来获取保存头像的路径

String url = request.getSession().getServletContext().getRealPath(

request.getRequestURI());

int a = url.lastIndexOf(File.separator);

url = url.substring(0, a);

id = request.getParameter("id");

TAttachment ta = (TAttachment) logic.load(TAttachment.class, id);

filepath = ta.getFilepath();

dirPaths = url + filepath;

// 读取文件

if (!"".equals(dirPaths)) {

ins = new FileInputStream(dirPaths);

int bytesRead = 0;

buffer = newbyte[4096];

response.setContentType("application/x-msdownload");

response.setHeader("Content-Disposition", "attachment;"

+ " filename="

+ new String(ta.getName().getBytes(), "ISO-8859-1"));

while ((bytesRead = ins.read(buffer, 0, 4096)) != -1) {

logic.write(response.getOutputStream(), buffer);

}

buffer = null;

ins.close();

}

} catch (Exception ex) {

request.setAttribute(Constants.C_ERROR_MSG, "文件下载出现错误");

return mapping.findForward("error");

}

returnnull;

}

6Byte转换为输入流

// 获取没有存入到硬盘的图片,然后把图片添加到硬盘

public ActionForward movePitureToDir(ActionMapping mapping,

ActionForm form, HttpServletRequest request,

HttpServletResponse response) throws Exception {

String outPath = "", fileName;

byte[] buffer = null;

OutputStream os = null;

byte[] bytes = newbyte[12];

byte[] bytes1;

Map map = new HashMap();

// 工程类路径,用来获取保存图片的路径

String url = request.getSession().getServletContext().getRealPath(request.getRequestURI());

int a = url.lastIndexOf(File.separator);

url = url.substring(0, a);

StringBuffer dirPath = new StringBuffer(url).append(File.separator).append("picture");

// 查找附件信息

List list = logic.getAttamentsByfilePath("/picture/circuitryPictrue");

if (list != null) {

// 创建文件夹picture

File fpath = new File(dirPath.toString());

if (!fpath.exists()) {

fpath.mkdir();

}

// 创建用户照片文件夹

dirPath.append("/").append("circuitryPictrue");

fpath = new File(dirPath.toString());

if (!fpath.exists()) {

fpath.mkdir();

}

dirPath.append("/");

for (int i = 0; i < list.size(); i++) {

map = (Map) list.get(i);

String id = map.get("id").toString();

TAttachment attaches = logic.getAttachment(id);

TCircuitry tc = (TCircuitry) logic.getDao().getHibernateTemplate().get(TCircuitry.class,attaches.getRelationid());

if (tc != null) {

StringBuffer strbf = new StringBuffer(dirPath);

// 创建某条线路的图片文件夹

strbf.append(tc.getCode());

fpath = new File(strbf.toString());

// 如果用户文件夹不存在,则创建用户文件夹

if (!fpath.exists()) {

fpath.mkdir();

}

// 获取图片的名字

fileName = attaches.getName();

strbf.append("/");

outPath = strbf.toString() + fileName;

if (!"".equals(attaches.getFilepath()) && attaches.getFilepath()!=null && !"".equals(attaches.getContexts()) && attaches.getContexts()!=null) {

bytes1 = attaches.getContexts();

//把字节转换为输入流

ByteArrayInputStream bis = new ByteArrayInputStream(bytes1);

os = new FileOutputStream(outPath);

buffer = newbyte[4096];

int len = 0;

while ((len = bis.read(buffer)) != -1) {

os.write(buffer, 0, len);

}

buffer = null;

bis.close();

os.close();

attaches.setFilepath("/picture/circuitryPictrue/"+ tc.getCode() + "/" + fileName);

attaches.setContexts(bytes);

logic.update(attaches);

}

} else {

logic.deleteAttachmentById(id);

}

}

}

returnthis.init(mapping, form, request, response);

}

7.删除文件夹中的文件

/**

*根据用户id查找图片,把没有存入磁盘的数据存入磁盘

*

*@parammapping

*@paramform

*@paramrequest

*@paramresponse

*@return

*@throwsException

*/

public ActionForward findPicture(ActionMapping mapping, ActionForm form,

HttpServletRequest request, HttpServletResponse response)

throws Exception {

String outPath = "", fileName;

byte[] buffer = null;

OutputStream os = null;

byte[] bytes = newbyte[12];

byte[] bytes1;

// 工程类路径,用来获取保存头像的路径

String url = request.getSession().getServletContext().getRealPath(

request.getRequestURI());

int a = url.lastIndexOf(File.separator);

url = url.substring(0, a);

StringBuffer dirPath = new StringBuffer(url).append(File.separator)

.append("picture");

UserBusIface service = (UserBusIface) this.getObject();

List list = service.getUnloadAttachement(FileTypeEnum.USERPIC,

"/picture/userPhoto");

if (list != null) {

// 创建文件夹picture

File fpath = new File(dirPath.toString());

if (!fpath.exists()) {

fpath.mkdir();

}

// 创建用户照片文件夹

dirPath.append("/").append("userPhoto");

fpath = new File(dirPath.toString());

if (!fpath.exists()) {

fpath.mkdir();

}

dirPath.append("/");

for (int i = 0; i < list.size(); i++) {

AttachmentPO attache = (AttachmentPO) list.get(i);

UserVO userpo = service.gainUserById(attache.getRelationId());

if (userpo != null) {

StringBuffer strbf = new StringBuffer(dirPath);

// 创建某个用户的图片文件夹

strbf.append(userpo.getCode());

fpath = new File(strbf.toString());

// 如果用户文件夹不存在,则创建用户文件夹

if (!fpath.exists()) {

fpath.mkdir();

} else {

// 调用删除文件夹及文件夹的内容方法

deleteAll[微软用户4](fpath);

fpath.mkdir();

}

// 获取图片的名字

fileName = attache.getName();

strbf.append("/");

outPath = strbf.toString() + fileName;

if (!"".equals(attache.getFilePath()) && attache.getFilePath()!=null && !"".equals(attache.getContexts()) && attache.getContexts()!=null) {

bytes1 = attache.getContexts();

ByteArrayInputStream bis = new ByteArrayInputStream(bytes1);

os = new FileOutputStream(outPath);

buffer = newbyte[4096];

int len = 0;

while ((len = bis.read(buffer)) != -1) {

os.write(buffer, 0, len);

}

buffer = null;

bis.close();

os.close();

attache.setFilePath("/picture/userPhoto/"

+ userpo.getCode() + "/" + fileName);

attache.setContexts(bytes);

service.update(attache);

}

}

}

}

returnthis.manageUserinfoPage(mapping, form, request, response);

}


[微软用户1] // 创建文件夹

privatevoid createdir(String code, StringBuffer dirPath) {

// 创建文件夹picture

File fpath = new File(dirPath.toString());

if (!fpath.exists()) {

fpath.mkdir();

}

// 创建用户照片文件夹

dirPath.append("/").append("circuitryPictrue");

fpath = new File(dirPath.toString());

if (!fpath.exists()) {

fpath.mkdir();

}

// 创建某个用户的图片文件夹

dirPath.append("/").append(code);

fpath = new File(dirPath.toString());

if (!fpath.exists()) {

fpath.mkdir();

}

}

[微软用户2] // 复制的方法

private String copyPicture(String code, String ip, String filePath,

String creatororgid, String creatorid, Set set_ta,

TAttachment tattBig, List attachement, StringBuffer dirPaths,

StringBuffer dirPath) throws FileNotFoundException, IOException {

String fileName;

String outPath;

int bytesRead;

byte[] buffer;

InputStream ins;

OutputStream os;

if (attachement != null && attachement.size() > 0) {

// 创建文件夹

createdir(code, dirPath);

TAttachment tatt = (TAttachment) attachement.get(0);

filePath = tatt.getFilepath();

// 获取图片路径和文件的名字

fileName = filePath.substring(filePath.lastIndexOf("\\") + 1);

int b = fileName.lastIndexOf("/") + 1;

fileName = fileName.substring(b);

dirPath.append("/");

outPath = dirPath.toString() + fileName;

// 写入文件

if (!"".equals(filePath)) {

ins = new FileInputStream(dirPaths + filePath);

os = new FileOutputStream(outPath);

bytesRead = 0;

buffer = newbyte[4096];

while ((bytesRead = ins.read(buffer, 0, 4096)) != -1) {

os.write(buffer, 0, bytesRead);

}

buffer = null;

os.close();

ins.close();

}

tattBig.setContexts(tatt.getContexts());

tattBig.setCreatetime(new Date());

tattBig.setCreatorid(creatorid);

tattBig.setCreatorip(ip);

tattBig.setCreatororgid(creatororgid);

tattBig.setExtend(tatt.getExtend());

tattBig.setFilepath("/picture/circuitryPictrue/" + code + "/"+ fileName);

tattBig.setFilesize(tatt.getFilesize());

tattBig.setKind(tatt.getKind());

tattBig.setName(tatt.getName());

tattBig.setType(tatt.getType());

set_ta.add(tattBig);

}

return filePath;

}

[微软用户3] // 处理同名的图片方法

private String picrename(String code, String filePath, String fileName,

TCircuitry po, List pathnameList, StringBuffer dirPaths,

String fileid) throws SysException {

File fpaths;

List attachetype;

TAttachment tat;

// 把传过来的图片路径字段查询附件,看是否存在相同的图片,如果有相同的,则添加到pathnameList

String filena = "/picture/circuitryPictrue/" + code + "/" + fileName;

List listpic = logic.getAttachmentbyId(po.getId(), filena);

if (listpic != null && listpic.size() > 0) {

TAttachment tatt = (TAttachment) listpic.get(0);

String filep = tatt.getFilepath();

int b = filep.lastIndexOf("/") + 1;

filep = filep.substring(b);

pathnameList.add(filep);

}

// 循环pathnameList判断是否有重名的图片

if (pathnameList != null && pathnameList.size() > 0) {

for (int i = 0; i < pathnameList.size(); i++) {

String beforFileName = (String) pathnameList.get(i);

if (fileid.equals("haveBigPic")

&& beforFileName.equals(fileName)) {

fileName = "big"+ i+ 1+ filePath

.substring(filePath.lastIndexOf("\\") + 1);

attachetype = logic.getAttachment(po.getId(), "BIGPIC");

if (attachetype != null && attachetype.size() > 0) {

tat = (TAttachment) attachetype.get(0);

// 删除图片磁盘原来的大图片

dirPaths = dirPaths.append(tat.getFilepath());

fpaths = new File(dirPaths.toString());

if (fpaths.exists()) {

fpaths.delete();

}

}

}

if (fileid.equals("haveLittlePic")

&& beforFileName.equals(fileName)) {

fileName = "little"

+ i

+ 1

+ filePath

.substring(filePath.lastIndexOf("\\") + 1);

attachetype = logic.getAttachment(po.getId(), "LITTLEPIC");

if (attachetype != null && attachetype.size() > 0) {

tat = (TAttachment) attachetype.get(0);

// 删除磁盘原来的小图片

dirPaths = dirPaths.append(tat.getFilepath());

fpaths = new File(dirPaths.toString());

if (fpaths.exists()) {

fpaths.delete();

}

}

}

else {

if (fileid.equals("haveBigPic")) {

attachetype = logic.getAttachment(po.getId(), "BIGPIC");

if (attachetype != null && attachetype.size() > 0) {

tat = (TAttachment) attachetype.get(0);

// 删除图片

dirPaths = dirPaths.append(tat.getFilepath());

fpaths = new File(dirPaths.toString());

if (fpaths.exists()) {

fpaths.delete();

}

}

}

if (fileid.equals("haveLittlePic")) {

attachetype = logic.getAttachment(po.getId(),

"LITTLEPIC");

if (attachetype != null && attachetype.size() > 0) {

tat = (TAttachment) attachetype.get(0);

// 删除图片

dirPaths = dirPaths.append(tat.getFilepath());

fpaths = new File(dirPaths.toString());

if (fpaths.exists()) {

fpaths.delete();

}

}

}

if (fileid.equals("haveWordFile")) {

attachetype = logic.getAttachment(po.getId(), "WORD");

if (attachetype != null && attachetype.size() > 0) {

tat = (TAttachment) attachetype.get(0);

// 删除图片

dirPaths = dirPaths.append(tat.getFilepath());

fpaths = new File(dirPaths.toString());

if (fpaths.exists()) {

fpaths.delete();

}

}

}

}

}

} else {

if (fileid.equals("haveBigPic")) {

attachetype = logic.getAttachment(po.getId(), "BIGPIC");

if (attachetype != null && attachetype.size() > 0) {

tat = (TAttachment) attachetype.get(0);

// 删除图片

dirPaths = dirPaths.append(tat.getFilepath());

fpaths = new File(dirPaths.toString());

if (fpaths.exists()) {

fpaths.delete();

}

}

}

if (fileid.equals("haveLittlePic")) {

attachetype = logic.getAttachment(po.getId(), "LITTLEPIC");

if (attachetype != null && attachetype.size() > 0) {

tat = (TAttachment) attachetype.get(0);

// 删除图片

dirPaths = dirPaths.append(tat.getFilepath());

fpaths = new File(dirPaths.toString());

if (fpaths.exists()) {

fpaths.delete();

}

}

}

if (fileid.equals("haveWordFile")) {

attachetype = logic.getAttachment(po.getId(), "WORD");

if (attachetype != null && attachetype.size() > 0) {

tat = (TAttachment) attachetype.get(0);

// 删除图片

dirPaths = dirPaths.append(tat.getFilepath());

fpaths = new File(dirPaths.toString());

if (fpaths.exists()) {

fpaths.delete();

}

}

}

}

return fileName;

}

[微软用户4] /**

*删除硬盘中文件夹中的方法

*

*@paramf

*/

publicstaticvoid deleteAll(File f) {

if (f.isFile()) {

f.delete();

} else {

// 获得当前文件夹下的所有子文件和子文件夹

File f1[] = f.listFiles();

// 循环处理每个对象

int len = f1.length;

for (int i = 0; i < len; i++) {

// 递归调用,处理每个文件对象

deleteAll(f1[i]);

}

// 删除当前文件夹

f.delete();

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值