惠普一体机怎么扫描的cpu在哪里。一体机的cpu能按到台式上么

主题信息(必填)
主题描述(最多限制在50个字符)
申请人信息(必填)
申请信息已提交审核,请注意查收邮件,我们会尽快给您反馈。
如有疑问,请联系
傻丫头和高科技产物小心翼翼的初恋
如今的编程是一场程序员和上帝的竞赛,程序员要开发出更大更好、傻瓜都会用到软件。而上帝在努力创造出更大更傻的傻瓜。目前为止,上帝是赢的。个人网站:。个人QQ群:、
个人大数据技术博客:
CSDN &《程序员》编辑/记者,投稿&纠错等事宜请致邮终于做回android功能了。这次主要介绍上传图片到服务端,服务端用socket或者servlet都可以,通常socket传的都是一些比较大的文件。我们先介绍servlet吧,服务端部分我也不算比较熟,都是借用人家的博客再作修改。我们先建立一个Dynamic Web Project。名字叫uploadImage,然后给个大致图。
还需要两个jar包。
服务端主要代码
UploadShipServlet.java:
package com.byl.
import java.io.BufferedInputS
import java.io.ByteArrayOutputS
import java.io.F
import java.io.FileOutputS
import java.io.IOE
import java.io.InputS
import java.io.PrintW
import java.util.L
import javax.servlet.ServletE
import javax.servlet.http.HttpS
import javax.servlet.http.HttpServletR
import javax.servlet.http.HttpServletR
import mons.fileupload.FileI
import mons.fileupload.disk.DiskFileItemF
import mons.fileupload.servlet.ServletFileU
public class UploadShipServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
public UploadShipServlet() {
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doPost(request, response);
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType(&text/charset=utf-8&);
request.setCharacterEncoding(&utf-8&);
response.setCharacterEncoding(&utf-8&);
PrintWriter out = response.getWriter();
// 创建文件项目工厂对象
DiskFileItemFactory factory = new DiskFileItemFactory();
// 设置文件上传路径
String upload = this.getServletContext().getRealPath(&/&);
// 获取系统默认的临时文件保存路径,该路径为Tomcat根目录下的temp文件夹
String temp = System.getProperty(&java.io.tmpdir&);
// 设置缓冲区大小为 5M
factory.setSizeThreshold(1024 * 1024 * 5);
// 设置临时文件夹为temp
factory.setRepository(new File(temp));
// 用工厂实例化上传组件,ServletFileUpload 用来解析文件上传请求
ServletFileUpload servletFileUpload = new ServletFileUpload(factory);
// 解析结果放在List中
List&FileItem& list = servletFileUpload.parseRequest(request);
for (FileItem item : list) {
String name = item.getFieldName();
InputStream is = item.getInputStream();
if (name.contains(&content&)) {
System.out.println(inputStream2String(is));
} else if (name.contains(&img&)) {
path = upload+&\\&+item.getName();
inputStream2File(is, path);
} catch (Exception e) {
e.printStackTrace();
out.write(path);
//这里我把服务端成功后,返回给客户端的是上传成功后路径
} catch (mons.fileupload.FileUploadException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
out.flush();
out.close();
// 流转化成字符串
public static String inputStream2String(InputStream is) throws IOException {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
int i = -1;
while ((i = is.read()) != -1) {
baos.write(i);
return baos.toString();
// 流转化成文件
public static void inputStream2File(InputStream is, String savePath) throws Exception {
System.out.println(&文件保存路径为:& + savePath);
File file = new File(savePath);
InputStream inputSteam =
BufferedInputStream fis = new BufferedInputStream(inputSteam);
FileOutputStream fos = new FileOutputStream(file);
while ((f = fis.read()) != -1) {
fos.write(f);
fos.flush();
fos.close();
fis.close();
inputSteam.close();
}web.xml:
&?xml version=&1.0& encoding=&UTF-8&?&
&web-app xmlns:xsi=&http://www.w3.org/2001/XMLSchema-instance& xmlns=&/xml/ns/javaee& xsi:schemaLocation=&/xml/ns/javaee /xml/ns/javaee/web-app_3_0.xsd& version=&3.0&&
&description&This is the description of my J2EE component&/description&
&display-name&This is the display name of my J2EE component&/display-name&
&servlet-name&UploadShipServlet&/servlet-name&
&servlet-class&com.byl.servlet.UploadShipServlet&/servlet-class&
&/servlet&
&servlet-mapping&
&servlet-name&UploadShipServlet&/servlet-name&
&url-pattern&/UploadShipServlet&/url-pattern&
&/servlet-mapping&
&/web-app&
index.jsp:&%@ page language=&java& import=&java.util.*& pageEncoding=&ISO-8859-1&%&
String path = request.getContextPath();
String basePath = request.getScheme()+&://&+request.getServerName()+&:&+request.getServerPort()+path+&/&;
&!DOCTYPE HTML PUBLIC &-//W3C//DTD HTML 4.01 Transitional//EN&&
&base href=&&%=basePath%&&&
&title&My JSP 'index.jsp' starting page&/title&
&meta http-equiv=&pragma& content=&no-cache&&
&meta http-equiv=&cache-control& content=&no-cache&&
&meta http-equiv=&expires& content=&0&&
&meta http-equiv=&keywords& content=&keyword1,keyword2,keyword3&&
&meta http-equiv=&description& content=&This is my page&&
&link rel=&stylesheet& type=&text/css& href=&styles.css&&
This is my JSP page. &br&
android客户端代码:
主要代码,这里用到别人封装好的工具类,方便调用。
public class UploadUtil {
private static final String TAG = &uploadFile&;
private static final int TIME_OUT = 10*1000;
//超时时间
private static final String CHARSET = &utf-8&; //设置编码
* android上传文件到服务器
* @param file
需要上传的文件
* @param RequestURL
返回响应的内容
public static String uploadFile(File file, String RequestURL){
String result =
BOUNDARY =
UUID.randomUUID().toString();
//边界标识
String PREFIX = &--& , LINE_END = &\r\n&;
String CONTENT_TYPE = &multipart/form-data&;
//内容类型
URL url = new URL(RequestURL);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(TIME_OUT);
conn.setConnectTimeout(TIME_OUT);
conn.setDoInput(true);
//允许输入流
conn.setDoOutput(true); //允许输出流
conn.setUseCaches(false);
//不允许使用缓存
conn.setRequestMethod(&POST&);
//请求方式
conn.setRequestProperty(&Charset&, CHARSET);
//设置编码
conn.setRequestProperty(&connection&, &keep-alive&);
conn.setRequestProperty(&Content-Type&, CONTENT_TYPE + &;boundary=& + BOUNDARY);
conn.connect();
if(file!=null){
* 当文件不为空,把文件包装并且上传
DataOutputStream dos = new DataOutputStream( conn.getOutputStream());
StringBuffer sb = new StringBuffer();
sb.append(PREFIX);
sb.append(BOUNDARY);
sb.append(LINE_END);
* 这里重点注意:
* name里面的值为服务器端需要key
只有这个key 才可以得到对应的文件
* filename是文件的名字,包含后缀名的
比如:abc.png
sb.append(&Content-Disposition: form- name=\&img\&; filename=\&&+file.getName()+&\&&+LINE_END);
sb.append(&Content-Type: application/octet- charset=&+CHARSET+LINE_END);
sb.append(LINE_END);
dos.write(sb.toString().getBytes());
InputStream is = new FileInputStream(file);
byte[] bytes = new byte[1024];
int len = 0;
while((len=is.read(bytes))!=-1){
dos.write(bytes, 0, len);
is.close();
dos.write(LINE_END.getBytes());
byte[] end_data = (PREFIX+BOUNDARY+PREFIX+LINE_END).getBytes();
dos.write(end_data);
dos.flush();
* 获取响应码
* 当响应成功,获取响应的流
int res = conn.getResponseCode();
if(res==200){
InputStream input =
conn.getInputStream();
StringBuffer sb1= new StringBuffer();
while((ss=input.read())!=-1){
sb1.append((char)ss);
result = sb1.toString();
System.out.println(result);
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
然后在上传的事件里面调用就可以了。
Data.getA()是图片的URL的路径,这样就完成了上传。是不是方便?
下面介绍socket的上传方法,服务端也是参考别人的。先建立一个java Project。
大致图是这样的:
socket服务端代码:
FileServer.java:
public class FileServer {
private ExecutorService executorS//线程池
//监听端口
private boolean quit =//退出
private ServerS
private Map&Long, FileLog& datas = new HashMap&Long, FileLog&();//存放断点数据
public FileServer(int port){
this.port =
//创建线程池,池中具有(cpu个数*50)条线程
executorService = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors() * 50);
public void quit(){
this.quit =
server.close();
} catch (IOException e) {
* 启动服务
* @throws Exception
public void start() throws Exception{
server = new ServerSocket(port);
while(!quit){
Socket socket = server.accept();
//为支持多用户并发访问,采用线程池管理每一个用户的连接请求
executorService.execute(new SocketTask(socket));
} catch (Exception e) {
e.printStackTrace();
private final class SocketTask implements Runnable{
private Socket socket =
public SocketTask(Socket socket) {
this.socket =
public void run() {
System.out.println(&accepted connection &+ socket.getInetAddress()+ &:&+ socket.getPort());
PushbackInputStream inStream = new PushbackInputStream(socket.getInputStream());
//得到客户端发来的第一行协议数据:Content-Length=;filename=xxx.3sourceid=
//如果用户初次上传文件,sourceid的值为空。
String head = StreamTool.readLine(inStream);
System.out.println(head);
if(head!=null){
//下面从协议数据中提取各项参数值
String[] items = head.split(&;&);
String filelength = items[0].substring(items[0].indexOf(&=&)+1);
String filename = items[1].substring(items[1].indexOf(&=&)+1);
String sourceid = items[2].substring(items[2].indexOf(&=&)+1);
long id = System.currentTimeMillis();//生产资源id,如果需要唯一性,可以采用UUID
FileLog log =
if(sourceid!=null && !&&.equals(sourceid)){
id = Long.valueOf(sourceid);
log = find(id);//查找上传的文件是否存在上传记录
File file =
int position = 0;
if(log==null){//如果不存在上传记录,为文件添加跟踪记录
String path = new SimpleDateFormat(&yyyy/MM/dd/HH/mm&).format(new Date());
File dir = new File(&file/&+ path);
if(!dir.exists()) dir.mkdirs();
file = new File(dir, filename);
if(file.exists()){//如果上传的文件发生重名,然后进行改名
filename = filename.substring(0, filename.indexOf(&.&)-1)+ dir.listFiles().length+ filename.substring(filename.indexOf(&.&));
file = new File(dir, filename);
save(id, file);
}else{// 如果存在上传记录,读取已经上传的数据长度
file = new File(log.getPath());//从上传记录中得到文件的路径
if(file.exists()){
File logFile = new File(file.getParentFile(), file.getName()+&.log&);
if(logFile.exists()){
Properties properties = new Properties();
properties.load(new FileInputStream(logFile));
position = Integer.valueOf(properties.getProperty(&length&));//读取已经上传的数据长度
OutputStream outStream = socket.getOutputStream();
String response = &sourceid=&+ id+ &;position=&+ position+ &\r\n&;
//服务器收到客户端的请求信息后,给客户端返回响应信息:sourceid=4;position=0
//sourceid由服务器端生成,唯一标识上传的文件,position指示客户端从文件的什么位置开始上传
outStream.write(response.getBytes());
RandomAccessFile fileOutStream = new RandomAccessFile(file, &rwd&);
if(position==0) fileOutStream.setLength(Integer.valueOf(filelength));//设置文件长度
fileOutStream.seek(position);//指定从文件的特定位置开始写入数据
byte[] buffer = new byte[1024];
int len = -1;
int length =
while( (len=inStream.read(buffer)) != -1){//从输入流中读取数据写入到文件中
fileOutStream.write(buffer, 0, len);
Properties properties = new Properties();
properties.put(&length&, String.valueOf(length));
FileOutputStream logFile = new FileOutputStream(new File(file.getParentFile(), file.getName()+&.log&));
properties.store(logFile, null);//实时记录已经接收的文件长度
logFile.close();
if(length==fileOutStream.length()) delete(id);
fileOutStream.close();
inStream.close();
outStream.close();
} catch (Exception e) {
e.printStackTrace();
if(socket!=null && !socket.isClosed()) socket.close();
} catch (IOException e) {}
public FileLog find(Long sourceid){
return datas.get(sourceid);
//保存上传记录
public void save(Long id, File saveFile){
//日后可以改成通过数据库存放
datas.put(id, new FileLog(id, saveFile.getAbsolutePath()));
//当文件上传完毕,删除记录
public void delete(long sourceid){
if(datas.containsKey(sourceid)) datas.remove(sourceid);
private class FileLog{
public Long getId() {
public void setId(Long id) {
public String getPath() {
public void setPath(String path) {
this.path =
public FileLog(Long id, String path) {
this.path =
然后是窗口代码ServerWindow.java:
public class ServerWindow extends Frame {
private FileServer s = new FileServer(12345);
public ServerWindow(String title) {
super(title);
label = new Label();
add(label, BorderLayout.PAGE_START);
label.setText(&服务器已经启动&);
this.addWindowListener(new WindowListener() {
public void windowOpened(WindowEvent e) {
new Thread(new Runnable() {
public void run() {
s.start();
} catch (Exception e) {
// e.printStackTrace();
}).start();
public void windowIconified(WindowEvent e) {
public void windowDeiconified(WindowEvent e) {
public void windowDeactivated(WindowEvent e) {
public void windowClosing(WindowEvent e) {
System.exit(0);
public void windowClosed(WindowEvent e) {
public void windowActivated(WindowEvent e) {
* @param args
public static void main(String[] args) throws IOException {
InetAddress address = InetAddress.getLocalHost();
ServerWindow window = new ServerWindow(&文件上传服务端:& + address.getHostAddress());
window.setSize(400, 300);
window.setVisible(true);
}最后是流解析的代码,StreamTool.java:public class StreamTool {
public static void save(File file, byte[] data) throws Exception {
FileOutputStream outStream = new FileOutputStream(file);
outStream.write(data);
outStream.close();
public static String readLine(PushbackInputStream in) throws IOException {
char buf[] = new char[128];
int room = buf.
int offset = 0;
while (true) {
switch (c = in.read()) {
case '\n':
case '\r':
int c2 = in.read();
if ((c2 != '\n') && (c2 != -1)) in.unread(c2);
if (--room & 0) {
char[] lineBuffer =
buf = new char[offset + 128];
room = buf.length - offset - 1;
System.arraycopy(lineBuffer, 0, buf, 0, offset);
buf[offset++] = (char)
if ((c == -1) && (offset == 0))
return String.copyValueOf(buf, 0, offset);
* @param inStream
* @return 字节数组
* @throws Exception
public static byte[] readStream(InputStream inStream) throws Exception{
ByteArrayOutputStream outSteam = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int len = -1;
while( (len=inStream.read(buffer)) != -1){
outSteam.write(buffer, 0, len);
outSteam.close();
inStream.close();
return outSteam.toByteArray();
服务端的代码差不多就这样啦。然后是客户端的代码:
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
private EditText edit_
private Button btn_
private Button btn_
private ProgressB
private TextView txt_
private UploadHelper upH
private boolean flag =
private Handler handler = new Handler() {
public void handleMessage(Message msg) {
pgbar.setProgress(msg.getData().getInt(&length&));
float num = (float) pgbar.getProgress() / (float) pgbar.getMax();
int result = (int) (num * 100);
txt_result.setText(result + &%&);
if (pgbar.getProgress() == pgbar.getMax()) {
Toast.makeText(MainActivity.this, &上传成功&, Toast.LENGTH_SHORT).show();
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
bindViews();
upHelper = new UploadHelper(this);
private void bindViews() {
edit_fname = (EditText) findViewById(R.id.edit_fname);
btn_upload = (Button) findViewById(R.id.btn_upload);
btn_stop = (Button) findViewById(R.id.btn_stop);
pgbar = (ProgressBar) findViewById(R.id.pgbar);
txt_result = (TextView) findViewById(R.id.txt_result);
btn_upload.setOnClickListener(this);
btn_stop.setOnClickListener(this);
public void onClick(View v) {
switch (v.getId()) {
case R.id.btn_upload:
String filename = edit_fname.getText().toString();
if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
File file = new File(Environment.getExternalStorageDirectory(), filename);
if (file.exists()) {
pgbar.setMax((int) file.length());
uploadFile(file);
Toast.makeText(MainActivity.this, &文件并不存在~&, Toast.LENGTH_SHORT).show();
Toast.makeText(MainActivity.this, &SD卡不存在或者不可用&, Toast.LENGTH_SHORT).show();
case R.id.btn_stop:
private void uploadFile(final File file) {
new Thread(new Runnable() {
public void run() {
String sourceid = upHelper.getBindId(file);
Socket socket = new Socket(&172.16.2.54&, 12345);
OutputStream outStream = socket.getOutputStream();
String head = &Content-Length=& + file.length() + &;filename=& + file.getName()
+ &;sourceid=& + (sourceid != null ? sourceid : &&) + &\r\n&;
outStream.write(head.getBytes());
PushbackInputStream inStream = new PushbackInputStream(socket.getInputStream());
String response = StreamTool.readLine(inStream);
String[] items = response.split(&;&);
String responseSourceid = items[0].substring(items[0].indexOf(&=&) + 1);
String position = items[1].substring(items[1].indexOf(&=&) + 1);
if (sourceid == null) {//如果是第一次上传文件,在数据库中不存在该文件所绑定的资源id
upHelper.save(responseSourceid, file);
RandomAccessFile fileOutStream = new RandomAccessFile(file, &r&);
fileOutStream.seek(Integer.valueOf(position));
byte[] buffer = new byte[1024];
int len = -1;
int length = Integer.valueOf(position);
while (flag && (len = fileOutStream.read(buffer)) != -1) {
outStream.write(buffer, 0, len);
length +=//累加已经上传的数据长度
Message msg = new Message();
msg.getData().putInt(&length&, length);
handler.sendMessage(msg);
if (length == file.length()) upHelper.delete(file);
fileOutStream.close();
outStream.close();
inStream.close();
socket.close();
} catch (Exception e) {
Toast.makeText(MainActivity.this, &上传异常~&, Toast.LENGTH_SHORT).show();
}).start();
}因为断点续传,我们需要保存上传的进度,我们需要用到数据库,这里我们定义一个数据库 管理类:
DBOpenHelper.java:
public class DBOpenHelper extends SQLiteOpenHelper {
public DBOpenHelper(Context context) {
super(context, &jay.db&, null, 1);
public void onCreate(SQLiteDatabase db) {
db.execSQL(&CREATE TABLE IF NOT EXISTS uploadlog (_id integer primary key autoincrement, path varchar(20), sourceid varchar(20))&);
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}然后是数据库操作类:UploadHelper.java:
public class UploadHelper {
private DBOpenHelper dbOpenH
public UploadHelper(Context context) {
dbOpenHelper = new DBOpenHelper(context);
public String getBindId(File file) {
SQLiteDatabase db = dbOpenHelper.getReadableDatabase();
Cursor cursor = db.rawQuery(&select sourceid from uploadlog where path=?&, new String[]{file.getAbsolutePath()});
if (cursor.moveToFirst()) {
return cursor.getString(0);
public void save(String sourceid, File file) {
SQLiteDatabase db = dbOpenHelper.getWritableDatabase();
db.execSQL(&insert into uploadlog(path,sourceid) values(?,?)&,
new Object[]{file.getAbsolutePath(), sourceid});
public void delete(File file) {
SQLiteDatabase db = dbOpenHelper.getWritableDatabase();
db.execSQL(&delete from uploadlog where path=?&, new Object[]{file.getAbsolutePath()});
}还要加上之前的流解析的类:
public class StreamTool {
public static void save(File file, byte[] data) throws Exception {
FileOutputStream outStream = new FileOutputStream(file);
outStream.write(data);
outStream.close();
public static String readLine(PushbackInputStream in) throws IOException {
char buf[] = new char[128];
int room = buf.
int offset = 0;
while (true) {
switch (c = in.read()) {
case '\n':
case '\r':
int c2 = in.read();
if ((c2 != '\n') && (c2 != -1)) in.unread(c2);
if (--room & 0) {
char[] lineBuffer =
buf = new char[offset + 128];
room = buf.length - offset - 1;
System.arraycopy(lineBuffer, 0, buf, 0, offset);
buf[offset++] = (char)
if ((c == -1) && (offset == 0))
return String.copyValueOf(buf, 0, offset);
* @param inStream
* @return 字节数组
* @throws Exception
public static byte[] readStream(InputStream inStream) throws Exception{
ByteArrayOutputStream outSteam = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int len = -1;
while( (len=inStream.read(buffer)) != -1){
outSteam.write(buffer, 0, len);
outSteam.close();
inStream.close();
return outSteam.toByteArray();
这样就好了。最后给上两个服务端的源码。客户端主要代码已经给出,这里不方便给出源码。
写得不好请多多见谅
&&相关文章推荐
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
访问:1103次
排名:千里之外发送私信成功
DevStore用户登录
还没有DevStore帐号?
快捷登录:
您目前的活力值不够下载该资源哦~~
怎么样快速获得活力值?
下载此资源将扣除活力值-20
(只在首次下载扣除活力值,之后可以免费下载)
满足所有需求,助您轻松工作
> 源码详情
android上传头像图片到服务器
15:00 && 浏览量(3222) &&
功能分类:生活
支持平台:Android
运行环境:Android
开发语言:Java
开发工具:Eclipse
源码大小:1.42MB
363 人下载
调用系统相机拍照,或者调用系统相册,把图片文件上传至服务器 【DEV技术哥测评:能在实体机和虚拟上运行,基本实现了截图上的效果,但必须去更改编码方式,否则会弹出乱码。】
选择图片来源
DevStore所有源码来自用户上传分享,版权问题及牵扯到商业纠纷均与DevStore无关。
* 显示修改头像的对话框
protected void showChoosePicDialog() {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("设置头像");
String[] items = { "选择本地照片", "拍照" };
builder.setNegativeButton("取消", null);
builder.setItems(items, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
switch (which) {
case CHOOSE_PICTURE: // 选择本地照片
Intent intent = new Intent(
Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
intent.setDataAndType(
MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
"image/*");
startActivityForResult(intent, CHOOSE_PICTURE);// //适用于4.4及以上android版本
case TAKE_PICTURE: // 拍照
Intent openCameraIntent = new Intent(
MediaStore.ACTION_IMAGE_CAPTURE);
tempUri = Uri.fromFile(new File(Environment
.getExternalStorageDirectory(), "image.jpg"));
// 指定照片保存路径(SD卡),image.jpg为一个临时文件,每次拍照后这个图片都会被替换
openCameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, tempUri);
startActivityForResult(openCameraIntent, TAKE_PICTURE);
builder.create().show();
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) { // 如果返回码是可以用的
switch (requestCode) {
case TAKE_PICTURE:
startPhotoZoom(tempUri); // 开始对图片进行裁剪处理
case CHOOSE_PICTURE:
startPhotoZoom(data.getData()); // 开始对图片进行裁剪处理
case CROP_SMALL_PICTURE:
if (data != null) {
setImageToView(data); // 让刚才选择裁剪得到的图片显示在界面上
* 裁剪图片方法实现
* @param uri
protected void startPhotoZoom(Uri uri) {
if (uri == null) {
Log.i("tag", "The uri is not exist.");
Intent intent = new Intent("com.android.camera.action.CROP");
intent.setDataAndType(uri, "image/*");
// 设置裁剪
intent.putExtra("crop", "true");
// aspectX aspectY 是宽高的比例
intent.putExtra("aspectX", 1);
intent.putExtra("aspectY", 1);
// outputX outputY 是裁剪图片宽高
intent.putExtra("outputX", 150);
intent.putExtra("outputY", 150);
intent.putExtra("return-data", true);
startActivityForResult(intent, CROP_SMALL_PICTURE);
* 保存裁剪之后的图片数据
* @param picdata
protected void setImageToView(Intent data) {
Bundle extras = data.getExtras();
if (extras != null) {
Bitmap photo = extras.getParcelable("data");
photo = Utils.toRoundBitmap(photo, tempUri); // 这个时候的图片已经被处理成圆形的了
iv_personal_icon.setImageBitmap(photo);
uploadPic(photo);
private void uploadPic(Bitmap bitmap) {
// 上传至服务器
// ... 可以在这里把Bitmap转换成file,然后得到file的url,做文件上传操作
// 注意这里得到的图片已经是圆形图片了
// bitmap是没有做个圆形处理的,但已经被裁剪了
imagePath = Utils.savePhoto(bitmap, Environment
.getExternalStorageDirectory().getAbsolutePath(), String
.valueOf(System.currentTimeMillis()));
Log.e("imagePath", imagePath + "");
if (imagePath != null) {
// 拿着imagePath上传了
Thread thread = new Thread(runnable);
thread.start();
/* 上传文件至Server的方法 */
private void uploadFile() {
String end = "\r\n";
String twoHyphens = "--";
String boundary = "*****";
URL url = new URL(actionUrl);//服务器地址
HttpURLConnection con = (HttpURLConnection) url.openConnection();
/* 允许Input、Output,不使用Cache */
con.setDoInput(true);
con.setDoOutput(true);
con.setUseCaches(false);
/* 设置传送的method=POST */
con.setRequestMethod("POST");
/* setRequestProperty *///设置请求属性
con.setRequestProperty("Connection", "Keep-Alive");
con.setRequestProperty("Charset", "UTF-8");
con.setRequestProperty("Content-Type",
"multipart/form-boundary=" + boundary);
/* 设置DataOutputStream *///数据输出流
//heading为服务器接收的键
DataOutputStream ds = new DataOutputStream(con.getOutputStream());
ds.writeBytes(twoHyphens + boundary + end);
ds.writeBytes("Content-Disposition: form- "
+ "name=\"headimg\";filename=\"" + newName + "\"" + end);
ds.writeBytes(end);
/* 取得文件的FileInputStream */ //文件输入流
fStream = new FileInputStream(imagePath);//要上传的图片路径,
/* 设置每次写入1024bytes */
int bufferSize = 1024;
byte[] buffer = new byte[bufferSize];
int length = -1;
/* 从文件读取数据至缓冲区 */
while ((length = fStream.read(buffer)) != -1) {
/* 将资料写入DataOutputStream中 */
ds.write(buffer, 0, length);
ds.writeBytes(end);
ds.writeBytes(twoHyphens + boundary + twoHyphens + end);
/* close streams */
fStream.close();
ds.flush();
/* 取得Response内容 */
InputStream is = con.getInputStream();
StringBuffer b = new StringBuffer();
while ((ch = is.read()) != -1) {
b.append((char) ch);
/* 将Response显示于Dialog */
showDialog("上传结果" + b.toString().trim());
Log.e("文件传输结果", b.toString().trim());
/* 关闭DataOutputStream */
ds.close();
} catch (Exception e) {
showDialog("上传失败" + e);
Log.i("败", "错误原因:" + e);
Runnable runnable = new Runnable() {
public void run() {
// TODO Auto-generated method stub
Looper.prepare();// 创建消息循环
uploadFile();
Message msg = new Message();
data.putString("image",
handler.sendMessage(msg);
Looper.loop();// 从消息队列取消
Handler handler = new Handler() {
public void handleMessage(Message msg) {
super.handleMessage(msg);
/* 显示Dialog的method */
private void showDialog(String mess) {
new AlertDialog.Builder(this).setTitle("Message").setMessage(mess)
.setNegativeButton("确定", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
}).show();
下载(363)
获取活力值
源码上传作者
资料下载排行
开发者交流群:
DevStore技术交流群2:
运营交流群:
产品交流群:
深圳尺子科技有限公司
深圳市南山区蛇口网谷万海大厦C栋504
Copyright (C) 2015 DevStore. All Rights Reserved

我要回帖

更多关于 惠普126a一体机 的文章

 

随机推荐