pbootcms网站模板|日韩1区2区|织梦模板||网站源码|日韩1区2区|jquery建站特效-html5模板网

  • <tfoot id='6lLcq'></tfoot>

      <small id='6lLcq'></small><noframes id='6lLcq'>

      • <bdo id='6lLcq'></bdo><ul id='6lLcq'></ul>

      <i id='6lLcq'><tr id='6lLcq'><dt id='6lLcq'><q id='6lLcq'><span id='6lLcq'><b id='6lLcq'><form id='6lLcq'><ins id='6lLcq'></ins><ul id='6lLcq'></ul><sub id='6lLcq'></sub></form><legend id='6lLcq'></legend><bdo id='6lLcq'><pre id='6lLcq'><center id='6lLcq'></center></pre></bdo></b><th id='6lLcq'></th></span></q></dt></tr></i><div class="i6i6yyy" id='6lLcq'><tfoot id='6lLcq'></tfoot><dl id='6lLcq'><fieldset id='6lLcq'></fieldset></dl></div>

    1. <legend id='6lLcq'><style id='6lLcq'><dir id='6lLcq'><q id='6lLcq'></q></dir></style></legend>
      1. 將圖像從android上傳到PHP服務器

        Uploading Image from android to PHP server(將圖像從android上傳到PHP服務器)
        • <small id='siHBk'></small><noframes id='siHBk'>

        • <tfoot id='siHBk'></tfoot><legend id='siHBk'><style id='siHBk'><dir id='siHBk'><q id='siHBk'></q></dir></style></legend>

          <i id='siHBk'><tr id='siHBk'><dt id='siHBk'><q id='siHBk'><span id='siHBk'><b id='siHBk'><form id='siHBk'><ins id='siHBk'></ins><ul id='siHBk'></ul><sub id='siHBk'></sub></form><legend id='siHBk'></legend><bdo id='siHBk'><pre id='siHBk'><center id='siHBk'></center></pre></bdo></b><th id='siHBk'></th></span></q></dt></tr></i><div class="h9bhnvr" id='siHBk'><tfoot id='siHBk'></tfoot><dl id='siHBk'><fieldset id='siHBk'></fieldset></dl></div>
            <bdo id='siHBk'></bdo><ul id='siHBk'></ul>

                    <tbody id='siHBk'></tbody>
                  本文介紹了將圖像從android上傳到PHP服務器的處理方法,對大家解決問題具有一定的參考價值,需要的朋友們下面隨著小編來一起學習吧!

                  問題描述

                  限時送ChatGPT賬號..

                  在我的應用程序中,我正在將圖像從我的設備上傳到本地網絡服務器...執行代碼后,會在服務器中創建一個 .jpg 文件,但不會打開它.并且服務器中文件的大小與原始文件不同.

                  In my app i am uploading an image from my device to a local web server... after executing the code a .jpg file gets created in the server but it does not gets opened. And the size of the file in server is different from the original file.

                  Android 活動:--

                  public class MainActivity extends Activity {
                  
                  
                  private static int RESULT_LOAD_IMAGE = 1;
                  @Override
                  protected void onCreate(Bundle savedInstanceState) {
                      super.onCreate(savedInstanceState);
                      setContentView(R.layout.activity_main);
                  
                      Button btnSelectImage=(Button) findViewById(R.id.uploadButton);
                      btnSelectImage.setOnClickListener(new OnClickListener() {
                  
                          @Override
                          public void onClick(View v) {
                  
                          Intent i=new   Intent(Intent.ACTION_PICK,android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                  
                          startActivityForResult(i, RESULT_LOAD_IMAGE);
                  
                          }
                      });
                  
                  }
                  
                  @Override
                  protected void onActivityResult(int requestCode, int resultCode, Intent data) {
                      // TODO Auto-generated method stub
                      super.onActivityResult(requestCode, resultCode, data);
                  
                      if (requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK && data!=null) {
                  
                          Uri selectedImage=data.getData();
                          String[] filePathColumn={MediaStore.Images.Media.DATA};
                  
                          Cursor cursor = getContentResolver().query(selectedImage,filePathColumn, null, null, null);
                          cursor.moveToFirst();
                  
                          int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
                          String picturePath = cursor.getString(columnIndex);
                          cursor.close();
                  
                  
                          Bitmap bitmap=BitmapFactory.decodeFile(picturePath);
                  
                          ImageView im = (ImageView) findViewById(R.id.imgBox);
                          im.setImageBitmap(bitmap);
                  
                          /*
                           * Convert the image to a string
                           * */
                          ByteArrayOutputStream stream = new ByteArrayOutputStream();
                          bitmap.compress(Bitmap.CompressFormat.PNG, 90, stream); //compress to which format you want.
                          byte [] byte_arr = stream.toByteArray();
                          String image_str = Base64.encodeToString(byte_arr,Base64.DEFAULT);
                  
                          /*
                           * Create a name value pair for the image string to be passed to the server
                           * */
                          ArrayList<NameValuePair> nameValuePairs = new  ArrayList<NameValuePair>();            
                          nameValuePairs.add(new BasicNameValuePair("image",image_str));
                  
                  
                          JSONObject jsonString=new JSONObject();
                          try {
                              jsonString.put("img", image_str);
                          } catch (JSONException e) {
                              // TODO Auto-generated catch block
                              e.printStackTrace();
                          }
                  
                          new uploadImageToPhp().execute(jsonString);
                  
                  
                  
                      }
                  
                  
                  }
                  @Override
                  public boolean onCreateOptionsMenu(Menu menu) {
                      // Inflate the menu; this adds items to the action bar if it is present.
                      getMenuInflater().inflate(R.menu.main, menu);
                  
                  
                      return true;
                  }
                  public class uploadImageToPhp extends AsyncTask<JSONObject, Void, Void>
                  {
                      String dataToSend=null;
                  
                      public static final String prefix="http://";                                                        //prefix of the urls
                      public static final String server_ip="172.16.26.155";                                                   //the ip address where the php server is located    
                  
                      public static final String completeServerAddress=prefix+server_ip+"/test_upload/upload_image.php";                  //Exact location of the php files
                  
                      @Override
                      protected Void doInBackground(JSONObject... params) {
                  
                          dataToSend="image="+params[0];
                          communicator(completeServerAddress, dataToSend);
                  
                  
                  
                  
                          return null;
                      }
                  
                      public void communicator(String urlString,String dataToSend2)
                      {
                          String result=null;
                  
                          try
                          {
                              URL url=new URL(urlString);
                              URLConnection conn=url.openConnection();
                  
                              HttpURLConnection httpConn=(HttpURLConnection) conn;
                              httpConn.setRequestProperty("Accept", "application/json");
                              httpConn.setRequestProperty("accept-charset", "UTF-8");
                              httpConn.setRequestMethod("POST");         
                              httpConn.connect();
                  
                              //Create an output stream to send data to the server
                              OutputStreamWriter out=new OutputStreamWriter(httpConn.getOutputStream());
                              out.write(dataToSend2);
                              out.flush();
                  
                              int httpStatus = httpConn.getResponseCode();            
                              System.out.println("Http status :"+httpStatus);
                  
                              if(httpStatus==HttpURLConnection.HTTP_OK)
                              {
                                  Log.d("HTTP STatus", "http connection successful");
                  
                                  BufferedReader in = new BufferedReader(new InputStreamReader(httpConn.getInputStream(),"UTF-8"));
                                  StringBuilder sb = new StringBuilder();
                                  String inputLine;
                                  while ((inputLine = in.readLine()) != null)
                                  {
                                      System.out.println(inputLine);
                                      sb.append(inputLine+"
                  ");
                                  }
                                  in.close();
                                  result=sb.toString();                       
                  
                                  try
                                  {
                  
                                      //jsonResult = new JSONObject(result);
                                  }
                                  catch(Exception e)
                                  {
                                       Log.e("JSON Parser", "Error parsing data " + e.toString());
                                  }
                  
                  
                              }
                              else
                              {
                                  System.out.println("Somthing went wrong");
                              }
                          } catch (MalformedURLException e) {
                              // TODO Auto-generated catch block
                              e.printStackTrace();
                          } catch (IOException e) {
                              // TODO Auto-generated catch block
                              e.printStackTrace();
                          }
                  
                  
                      }
                  
                  
                  }
                  
                  }
                  

                  PHP 代碼:-

                   $recievedJson=$_REQUEST['image'];
                  $imageContent=json_decode($recievedJson,true);
                   $base=$imageContent["img"];
                  
                   $binary=base64_decode($base);
                  
                   echo $binary;
                  header('Content-Type: bitmap; charset=utf-8');
                  $file = fopen('uploaded_image.jpg', 'wb');
                  fwrite($file, $binary);
                  fclose($file);
                  

                  推薦答案

                  使用下面的代碼.它會做同樣的事情.

                  Use below code. It will do the same.

                  public class UploadImage extends Activity {
                      InputStream inputStream;
                          @Override
                      public void onCreate(Bundle icicle) {
                              super.onCreate(icicle);
                              setContentView(R.layout.main);
                  
                              Bitmap bitmap = BitmapFactory.decodeResource(getResources(),R.drawable.icon);           ByteArrayOutputStream stream = new ByteArrayOutputStream();
                              bitmap.compress(Bitmap.CompressFormat.PNG, 90, stream); //compress to which format you want.
                              byte [] byte_arr = stream.toByteArray();
                              String image_str = Base64.encodeBytes(byte_arr);
                              ArrayList<NameValuePair> nameValuePairs = new  ArrayList<NameValuePair>();
                  
                              nameValuePairs.add(new BasicNameValuePair("image",image_str));
                  
                               Thread t = new Thread(new Runnable() {
                  
                              @Override
                              public void run() {
                                    try{
                                           HttpClient httpclient = new DefaultHttpClient();
                                           HttpPost httppost = new HttpPost("server-link/folder-name/upload_image.php");
                                           httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
                                           HttpResponse response = httpclient.execute(httppost);
                                           String the_string_response = convertResponseToString(response);
                                           runOnUiThread(new Runnable() {
                  
                                                  @Override
                                                  public void run() {
                                                      Toast.makeText(UploadImage.this, "Response " + the_string_response, Toast.LENGTH_LONG).show();                          
                                                  }
                                              });
                  
                                       }catch(Exception e){
                                            runOnUiThread(new Runnable() {
                  
                                              @Override
                                              public void run() {
                                                  Toast.makeText(UploadImage.this, "ERROR " + e.getMessage(), Toast.LENGTH_LONG).show();                              
                                              }
                                          });
                                             System.out.println("Error in http connection "+e.toString());
                                       }  
                              }
                          });
                           t.start();
                          }
                  
                          public String convertResponseToString(HttpResponse response) throws IllegalStateException, IOException{
                  
                               String res = "";
                               StringBuffer buffer = new StringBuffer();
                               inputStream = response.getEntity().getContent();
                               int contentLength = (int) response.getEntity().getContentLength(); //getting content length…..
                                runOnUiThread(new Runnable() {
                  
                              @Override
                              public void run() {
                                  Toast.makeText(UploadImage.this, "contentLength : " + contentLength, Toast.LENGTH_LONG).show();                     
                              }
                          });
                  
                               if (contentLength < 0){
                               }
                               else{
                                      byte[] data = new byte[512];
                                      int len = 0;
                                      try
                                      {
                                          while (-1 != (len = inputStream.read(data)) )
                                          {
                                              buffer.append(new String(data, 0, len)); //converting to string and appending  to stringbuffer…..
                                          }
                                      }
                                      catch (IOException e)
                                      {
                                          e.printStackTrace();
                                      }
                                      try
                                      {
                                          inputStream.close(); // closing the stream…..
                                      }
                                      catch (IOException e)
                                      {
                                          e.printStackTrace();
                                      }
                                      res = buffer.toString();     // converting stringbuffer to string…..
                  
                                      runOnUiThread(new Runnable() {
                  
                                      @Override
                                      public void run() {
                                         Toast.makeText(UploadImage.this, "Result : " + res, Toast.LENGTH_LONG).show();
                                      }
                                  });
                                      //System.out.println("Response => " +  EntityUtils.toString(response.getEntity()));
                               }
                               return res;
                          }
                  }
                  

                  PHP 代碼

                  <?php
                      $base=$_REQUEST['image'];
                       $binary=base64_decode($base);
                      header('Content-Type: bitmap; charset=utf-8');
                      $file = fopen('uploaded_image.jpg', 'wb');
                      fwrite($file, $binary);
                      fclose($file);
                      echo 'Image upload complete!!, Please check your php file directory……';
                  ?>
                  

                  更新

                  NameValuePair 和 Http 類已被棄用,所以我已經嘗試過這段代碼,它對我有用.希望有幫助!

                  NameValuePair and Http Classes are deprecated so, I've tried this code and it's working for me. Hope that helps!

                  private void uploadImage(Bitmap imageBitmap){
                      ByteArrayOutputStream stream = new ByteArrayOutputStream();
                      imageBitmap.compress(Bitmap.CompressFormat.PNG, 90, stream);
                      byte[] b = stream.toByteArray();
                      String encodedImage = Base64.encodeToString(b, Base64.DEFAULT);
                      ArrayList<Pair<String, String>> params = new ArrayList<Pair<String, String>>();
                      params.add(new Pair<>("image", encodedImage));
                  
                      try {
                          new AsyncUploader().execute(my_upload_php, getQuery(params));
                      } catch (UnsupportedEncodingException e) {
                          e.printStackTrace();
                      }
                  }
                  
                  private String getQuery(List<Pair<String, String>> params) throws UnsupportedEncodingException{
                      StringBuilder result = new StringBuilder();
                      boolean first = true;
                  
                      for(Pair<String, String> pair : params){
                          if(first)
                              first = false;
                          else
                              result.append("&");
                  
                          result.append(URLEncoder.encode(pair.first, "UTF-8"));
                          result.append("=");
                          result.append(URLEncoder.encode(pair.second, "UTF-8"));
                      }
                      return result.toString();
                  }
                  
                  private class AsyncUploader extends AsyncTask<String, Integer, String>
                  {
                      @Override
                      protected String doInBackground(String... strings) {
                          String urlString = strings[0];
                          String params = strings[1];
                          URL url = null;
                          InputStream stream = null;
                          HttpURLConnection urlConnection = null;
                          try {
                              url = new URL(urlString);
                              urlConnection = (HttpURLConnection) url.openConnection();
                              urlConnection.setRequestMethod("POST");
                              urlConnection.setDoOutput(true);
                  
                              urlConnection.connect();
                  
                              OutputStreamWriter wr = new OutputStreamWriter(urlConnection.getOutputStream());
                              wr.write(params);
                              wr.flush();
                  
                              stream = urlConnection.getInputStream();
                              BufferedReader reader = new BufferedReader(new InputStreamReader(stream, "UTF-8"), 8);
                              String result = reader.readLine();
                              return result;
                          }catch (IOException ioe){
                              ioe.printStackTrace();
                          } finally {
                              if (urlConnection != null)
                                  urlConnection.disconnect();
                          }
                          return null;
                      }
                  
                      @Override
                      protected  void onPostExecute(String result) {
                          Toast.makeText(MakePhoto.this, result, Toast.LENGTH_SHORT).show();
                      }
                  }
                  

                  這篇關于將圖像從android上傳到PHP服務器的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!

                  【網站聲明】本站部分內容來源于互聯網,旨在幫助大家更快的解決問題,如果有圖片或者內容侵犯了您的權益,請聯系我們刪除處理,感謝您的支持!

                  相關文檔推薦

                  enable SOAP on PHP(在 PHP 上啟用 SOAP)
                  Get received XML from PHP SOAP Server(從 PHP SOAP 服務器獲取接收到的 XML)
                  not a valid AllXsd value(不是有效的 AllXsd 值)
                  PHP SoapClient: SoapFault exception Could not connect to host(PHP SoapClient:SoapFault 異常無法連接到主機)
                  Implementation of P_SHA1 algorithm in PHP(PHP中P_SHA1算法的實現)
                  Sending a byte array from PHP to WCF(將字節數組從 PHP 發送到 WCF)
                    <tbody id='z5DJB'></tbody>
                      <bdo id='z5DJB'></bdo><ul id='z5DJB'></ul>
                      <legend id='z5DJB'><style id='z5DJB'><dir id='z5DJB'><q id='z5DJB'></q></dir></style></legend>
                    • <i id='z5DJB'><tr id='z5DJB'><dt id='z5DJB'><q id='z5DJB'><span id='z5DJB'><b id='z5DJB'><form id='z5DJB'><ins id='z5DJB'></ins><ul id='z5DJB'></ul><sub id='z5DJB'></sub></form><legend id='z5DJB'></legend><bdo id='z5DJB'><pre id='z5DJB'><center id='z5DJB'></center></pre></bdo></b><th id='z5DJB'></th></span></q></dt></tr></i><div class="h1vhdtp" id='z5DJB'><tfoot id='z5DJB'></tfoot><dl id='z5DJB'><fieldset id='z5DJB'></fieldset></dl></div>

                          <small id='z5DJB'></small><noframes id='z5DJB'>

                            <tfoot id='z5DJB'></tfoot>
                            主站蜘蛛池模板: 深圳品牌设计公司-LOGO设计公司-VI设计公司-未壳创意 | 防锈油-助焊剂-光学玻璃清洗剂-贝塔防锈油生产厂家 | 深圳办公室装修,办公楼/写字楼装修设计,一级资质 - ADD写艺 | 大通天成企业资质代办_承装修试电力设施许可证_增值电信业务经营许可证_无人机运营合格证_广播电视节目制作许可证 | 激光内雕_led玻璃_发光玻璃_内雕玻璃_导光玻璃-石家庄明晨三维科技有限公司 激光内雕-内雕玻璃-发光玻璃 | 嘉兴泰东园林景观工程有限公司_花箱护栏 | 光纤测温-荧光光纤测温系统-福州华光天锐光电科技有限公司 | 青岛美佳乐清洁工程有限公司|青岛油烟管道清洗|酒店|企事业单位|学校工厂厨房|青岛油烟管道清洗 插针变压器-家用电器变压器-工业空调变压器-CD型电抗器-余姚市中驰电器有限公司 | 工业铝型材-铝合金电机壳-铝排-气动执行器-山东永恒能源集团有限公司 | 雨水收集系统厂家-雨水收集利用-模块雨水收集池-徐州博智环保科技有限公司 | 成都思迪机电技术研究所-四川成都思迪编码器 | 磁力去毛刺机_去毛刺磁力抛光机_磁力光饰机_磁力滚抛机_精密金属零件去毛刺机厂家-冠古科技 | 电磁辐射仪-电磁辐射检测仪-pm2.5检测仪-多功能射线检测仪-上海何亦仪器仪表有限公司 | 金属清洗剂,防锈油,切削液,磨削液-青岛朗力防锈材料有限公司 | 除尘器布袋骨架,除尘器滤袋,除尘器骨架,电磁脉冲阀膜片,卸灰阀,螺旋输送机-泊头市天润环保机械设备有限公司 | BESWICK球阀,BESWICK接头,BURKERT膜片阀,美国SEL继电器-东莞市广联自动化科技有限公司 | ★塑料拖链__工程拖链__电缆拖链__钢制拖链 - 【上海闵彬】 | 外贮压-柜式-悬挂式-七氟丙烷-灭火器-灭火系统-药剂-价格-厂家-IG541-混合气体-贮压-非贮压-超细干粉-自动-灭火装置-气体灭火设备-探火管灭火厂家-东莞汇建消防科技有限公司 | 北京律师咨询_知名专业北京律师事务所_免费法律咨询 | 紧急切断阀_气动切断阀_不锈钢阀门_截止阀_球阀_蝶阀_闸阀-上海上兆阀门制造有限公司 | 2025世界机器人大会_IC China_半导体展_集成电路博览会_智能制造展览网 | 锡膏喷印机-全自动涂覆机厂家-全自动点胶机-视觉点胶机-深圳市博明智控科技有限公司 | 广州展览设计公司_展台设计搭建_展位设计装修公司-众派展览装饰 广州展览制作工厂—[优简]直营展台制作工厂_展会搭建资质齐全 | 语料库-提供经典范文,文案句子,常用文书,您的写作得力助手 | 南京办公用品网-办公文具用品批发-打印机耗材采购 | 武汉画册印刷厂家-企业画册印刷-画册设计印刷制作-宣传画册印刷公司 - 武汉泽雅印刷厂 | 北京办公室装修,办公室设计,写字楼装修-北京金视觉装饰工程公司 北京成考网-北京成人高考网 | 淘剧影院_海量最新电视剧,免费高清电影随心观看 | 精准猎取科技资讯,高效阅读科技新闻_科技猎 | 优宝-汽车润滑脂-轴承润滑脂-高温齿轮润滑油脂厂家 | 江西自考网-江西自学考试网| 心得体会网_心得体会格式范文模板 | 镀锌方管,无缝方管,伸缩套管,方矩管_山东重鑫致胜金属制品有限公司 | WTB5光栅尺-JIE WILL磁栅尺-B60数显表-常州中崴机电科技有限公司 | PCB接线端子_栅板式端子_线路板连接器_端子排生产厂家-置恒电气 喷码机,激光喷码打码机,鸡蛋打码机,手持打码机,自动喷码机,一物一码防伪溯源-恒欣瑞达有限公司 假肢-假肢价格-假肢厂家-河南假肢-郑州市力康假肢矫形器有限公司 | 灌木树苗-绿化苗木-常绿乔木-价格/批发/基地 - 四川成都途美园林 | 同步带轮_同步带_同步轮_iHF合发齿轮厂家-深圳市合发齿轮机械有限公司 | 杭州实验室尾气处理_实验台_实验室家具_杭州秋叶实验设备有限公司 | 水冷式工业冷水机组_风冷式工业冷水机_水冷螺杆冷冻机组-深圳市普威机械设备有限公司 | 施工围挡-施工PVC围挡-工程围挡-深圳市旭东钢构技术开发有限公司 | 土壤检测仪器_行星式球磨仪_土壤团粒分析仪厂家_山东莱恩德智能科技有限公司 |