Here I posted some java client code and php server-side code, you help me find out where the problem:
public class myThread extends Thread{
@Override
public void run() {
// TODO Auto-generated method stub
String r = null;
upload_fail = new ArrayList<HashMap<String, String>>();
if (!catid.equals(null)) {
for (HashMap<String, String> map : path_list) {
String path = map.get("img_path");
Bitmap bit = BitmapFactory.decodeFile(path);
float pc = (float) 100 / (float) bit.getWidth();//压缩比例
Bitmap bit2 = resize_img(bit, pc);//压缩bitmap
String filename = path.substring(path.lastIndexOf("/") + 1);
File file = saveMyBitmap(filename, bit2);
//File file = new File(path);//若上传原图则用这一行代码代替上面5行即可
upload_res = UploadUtil.uploadFile(file, pc, actionUrl, catid, s_sessid, s_psnId);//上传(返回一个HashMap)
String result = upload_res.get("ans").toString();
if (!result.equals("success")) {
//失败
HashMap<String, String> fail_map = new HashMap<String, String>();
fail_map.put("name", file.getName());
fail_map.put("path", path);
upload_fail.add(fail_map);
} else {
//成功
file.delete();
bit2.recycle();
bit2 = null;
System.gc();
upload_success.add(map.get("thrum_path"));
}
}
s_psnId = upload_res.get("sess_psnId").toString();
s_sessid = upload_res.get("sessionId").toString();
if (upload_fail.size() == 0) {
//全部成功
r = "success";
}else {
if (upload_success.size() == 0) {
//全部失败
r = upload_res.get("ans").toString();
} else {
//部分失败
r = "对不起,图片 [ ";
for (HashMap<String, String> map : upload_fail) {
r += map.get("name") + " ";
}
r += "] 上传失败!";
}
}
} else {
r = "请选择相册";
}
Message msg = myHand.obtainMessage();
Bundle b = new Bundle();
b.putString("res", r);
msg.setData(b);
myHand.sendMessage(msg);
}
}
//压缩bitmap
private Bitmap resize_img(Bitmap bitmap, float pc) {
Matrix matrix = new Matrix();
Log.i("mylog2", "缩放比例--" + pc);
matrix.postScale(pc, pc); // 长和宽放大缩小的比例
Bitmap resizeBmp = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(),
bitmap.getHeight(), matrix, true);
bitmap.recycle();
bitmap = null;
System.gc();
int width = resizeBmp.getWidth();
int height = resizeBmp.getHeight();
Log.i("mylog2", "按比例缩小后宽度--" + width);
Log.i("mylog2", "按比例缩小后高度--" + height);
return resizeBmp;
}
//将压缩的bitmap保存到sdcard卡临时文件夹img_interim,用于上传
@SuppressLint("SdCardPath")
public File saveMyBitmap(String filename, Bitmap bit) {
File dir = new File("/sdcard/img_interim/");
if (!dir.exists()) {
dir.mkdir();
}
File f = new File("/sdcard/img_interim/" + filename);
try {
f.createNewFile();
FileOutputStream fOut = null;
fOut = new FileOutputStream(f);
bit.compress(Bitmap.CompressFormat.PNG, 100, fOut);
fOut.flush();
fOut.close();
} catch (IOException e1) {
// TODO Auto-generated catch block
f = null;
e1.printStackTrace();
}
return f;
}
Here is upload tool category code:
public class UploadUtil {
private static final String TAG = "mylog2";
private static final int TIME_OUT = 10 * 1000; // 超时时间
private static final String CHARSET = "utf-8"; // 设置编码
/**
*
* 上传文件到服务器
* @param file 需要上传的文件
* @param RequestURL 请求的rul
* @return 返回响应的内容
*/
public static HashMap<String, Object> uploadFile(File file, float pc, String RequestURL,
String catid, String sessionid, String psnid) {
HashMap<String, Object> response_map = new HashMap<String, Object>();
int res = 0;
String result = null;
String BOUNDARY = UUID.randomUUID().toString(); // 边界标识 随机生成
String PREFIX = "--", LINE_END = "\r\n";
String CONTENT_TYPE = "multipart/form-data"; // 内容类型
try {
RequestURL += "?sessionId=" + sessionid + "&sess_psnId=" + psnid;
RequestURL += "&catid=" + catid + "&pc=" + pc;
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("GET"); // 请求方式
conn.setInstanceFollowRedirects(true);
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);
sb.append("Content-Disposition: form-data; name=\"uploadedimg\"; filename=\""
+ file.getName() + "\"" + LINE_END);
sb.append("Content-Type: application/octet-stream; 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();
//获取响应码 200=成功 当响应成功,获取响应的流
res = conn.getResponseCode();
if (res == 200) {
InputStream input = conn.getInputStream();
StringBuffer sb1 = new StringBuffer();
int ss;
while ((ss = input.read()) != -1) {
sb1.append((char) ss);
}
result = sb1.toString();
Log.i("mylog2", "--" + result);
result = result.substring(result.indexOf("{"));
try {
JSONObject obj = new JSONObject(result);
String info = obj.getString("ans");
if (info.equals("success")) {
response_map.put("catid", obj.getString("catid"));
}
response_map.put("ans", info);
response_map.put("sessionId", obj.getString("sessionid"));
response_map.put("sess_psnId", obj.getString("session_psn_id"));
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} else {
Log.e(TAG, "request error");
}
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return response_map;
}
}
php server-side code:
$ans = array();
$pc = $_GET['pc'];
$ans['ans'] = "";
if (isset($_FILES['uploadedimg'])) {
$target_path = $_SERVER['DOCUMENT_ROOT']."/uploads/";//接收文件目录
$file_name = basename($_FILES['uploadedimg']['name']);
$str = explode('.', $file_name);
$img_type = $str[count($str) - 1];
$target_path .= $file_name;
if (move_uploaded_file($_FILES['uploadedimg']['tmp_name'], $target_path)) {
$src_info = @getimagesize($target_path);
$src_w = $src_info[0];
$src_h = $src_info[1];
$dst_w = $src_w / $pc;
$dst_h = $src_h / $pc;
$ans['imginfo'] = round($dst_w) . "--" + round($dst_h);
if($img_type == "jpg" || $img_type == "jpeg") {
$img_ty = 1;
$src_im = imagecreatefromjpeg($target_path);
} else if ($img_type == "png") {
$img_ty = 2;
$src_im = imagecreatefrompng($target_path);
} else if ($img_type == "gif") {
$img_ty = 3;
$src_im = imagecreatefromgif($target_path);
}
$dst_im = imagecreatetruecolor(round($dst_w), round($dst_h));
$bg = imagecolorallocate($dst_im, 255, 255, 255);
imagefill($dst_im, 0, 0, $bg);
imagecopyresampled($dst_im, $src_im, 0, 0, 0, 0, $dst_w, $dst_h, $src_w, $src_h);
switch ($img_ty) {
case 1 :
imagejpeg($dst_im, $target_path, 100);
$ans['ans'] = "success";
break;
case 2 :
imagepng($dst_im, $target_path);
$ans['ans'] = "success";
break;
case 3 :
imagegif($dst_im, $target_path);
$ans['ans'] = "success";
break;
default :
$ans['ans'] = "格式无法识别";
}
}
}
echo json_encode($ans);
finally get the picture size consistent with the original, but a serious distortion
------ Solution ------- -------------------------------------
http://bbs.csdn.net/ topics/390432950 refer to this post
------ reference -------------------------------- -------
seemingly compression will be distorted
------ reference ------------------------- --------------
Hello, reference to provide you with this post came to understand resize_img () The width and height of the bitmap compression method superfluous
just need to keep saveMyBitmap ()
change bit.compress (Bitmap.CompressFormat.JPEG, 100, fOut); This 100 This value can be
But the reference quote, you put a chunk of code that is also why the compression KB in size before the picture width and height is compressed it?
This is used to upload it?
I was doing the project learning android, had no contact with android, self-learning ability is really not very good, almost six months on many issues are still not aware that many functions even if made out is shining online check the information follow suit, and for the principle, but not to explore too, so for android, basically illiterate
do now picture upload, picture upload is successful, but for compression piece, check the internet a lot of information, are the width and height of the picture compression
It was felt strange: Wide high compression, the picture is not original size, then zoom should also Distortion
I was also wondering if you're simply not used to upload, but only on the phone screen is used to display only
information can be found very clearly shows is used to upload, so I think that when the server decompress any particular method allows images without distortion
Now I know change bit.compress (Bitmap.CompressFormat.JPEG, 100, fOut); 100 this value can be compressed KB in size without affecting the image width and height and clarity.
compression KB in size but the picture width and height before compression, which can explain what is why? Upload pictures so I mentioned in the post is not just the case that: If the background does not deal directly saved pass over the pictures, so pictures will be much smaller than the original; if background amplification processing, the pass over the consistent with the original image to enlarge, image will be seriously distorted
------ reference --------------------------- ------------
distortion certainly will happen, and this you have to select a range, both to ensure quality, guaranteed upload, considering that you need to own.
------ reference - --------------------------------------
Oh, I see. I would like to ask when I upload the compressed bitmap into File saved sdcard card and then upload [saveMyBitmap (String filename, Bitmap bit)], and then delete the uploaded successfully
Is there any way you can not save to sd card, direct upload files it
------ reference --------------------- ------------------
Oh, I see. I would like to ask when I upload the compressed bitmap into File saved sdcard card and then upload [saveMyBitmap (String filename, Bitmap bit)], and then delete the uploaded successfully
Is there any way you can not save to sd card, upload it directly
Oh, I see. I would like to ask when I upload the compressed bitmap into File saved sdcard card and then upload [saveMyBitmap (String filename, Bitmap bit)], and then delete the uploaded successfully
Is there any way you can not save to sd card, upload it directly
you that picture came from Well
------ reference --------------------------- ------------
temporary files can be placed in / data / data / yourpackage / files directory, I forgot the specific methods that you can see Soso
After the upload is complete and then delete the OK
------ reference ---------------------------- -----------
Thank you
------ reference - --------------------------------------
Hello I am a rookie, can pack Source issuing to me, thank you ah 709530851@qq.com Jiqiu a android upload images to php server case, thank you!
没有评论:
发表评论