1

我有一个要求,我将一个 json 文件发送到服务器,并且解析发生在服务器端。我已经创建了 json 文件的条目,现在我想将存储在 imageview 中的图像存储为 json 文件的条目。搜索了几个以前的帖子,但找不到确切的内容。任何指针对于以 json 格式存储图像以通过服务器发送都会有很大帮助。

4

4 回答 4

10

如果您想将 Image 包含在您将在请求中发送的 JSON 对象中,请将 Image 转换为 Base64 字符串并将此字符串放入 JSON 对象中。

例如:

String encodedImage = Base64.encodeToString(byteArrayImage, Base64.DEFAULT);

查看:

于 2013-03-22T08:41:53.823 回答
2

尝试对图像进行 base64 编码(如下所示,Uri 是您的图像 - 但请注意:ImageView 没有用于 ImageUri 的 Getter,因此您必须自己存储它!):

Uri uri = (Uri) extras.getParcelable(Intent.EXTRA_STREAM);

ContentResolver cr = getContentResolver();
InputStream is = cr.openInputStream(uri);

byte[] data = getBytesFromFile(is);

byte[] encoded_data = Base64.encodeBase64(data);
data_string = new String(encoded_data);

现在您有了一个 base64 编码的字符串data_string,您可以将它与您的 JSON 请求一起发送。在服务器端,您只需解码字符串并保存图片。

于 2013-03-22T08:40:26.800 回答
1

嗯,这是一种实验性的方法,但是您可以从位图中创建一个字节数组,然后使用该字节数组创建一个新字符串,然后将其发送到服务器。

但是,为什么不直接发送一个 POST 请求来保存图像,而不进行任何实验处理或解析呢?

于 2013-03-22T08:40:19.403 回答
0

你有一个 ImageView

<ImageView
      android:layout_width = "300dp"
      android:layout_height = "300dp"
      android:id = "@+id/Plaatjeid"
      android:scaleType = "centerCrop"
    android:text = "@string/BerttxtPlaatje"
    android:layout_alignParentEnd="true"
/>

在代码隐藏中

String plaatje="";
ImageView iv1 = (ImageView)findViewById(R.id.Plaatjeid);
    iv1.buildDrawingCache();
    Bitmap bitmap = iv1.getDrawingCache();
    ByteArrayOutputStream stream=new ByteArrayOutputStream();
    bitmap.compress(Bitmap.CompressFormat.PNG, 90, stream);
    byte[] image=stream.toByteArray();
    plaatje = Base64.encodeToString(image, 0);

然后你创建你的 Json 字符串

String mailMessage;
mailMessage="<?xml version='1.0'?>";
mailMessage=mailMessage + "<RiscNotification xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'";
mailMessage=mailMessage + "xmlns:xsd='htp://www.w3.org/2001/XMLSchema'>";
mailMessage = mailMessage + "        <mail To>"  + Mailto() + "</mail To>" ;//server7
mailMessage = mailMessage + "</RiskNotification>";

我有一个单独的类,我在其中发送它 将变量附加到类

GetMethodDemo JsonConnect = new GetMethodDemo();
JsonConnect.MailTo=  Mailto();
JsonConnect.Picture=plaatje;
JsonConnect.bertactivity=this;
JsonConnect.execute();//staat in AANHET BEGIN

和我的班级

    package nl.yentel.finekinney;
    import java.io.BufferedReader;
    import java.io.InputStreamReader;
    import java.io.OutputStream;
    import java.net.HttpURLConnection;
    import java.net.URL;

    import android.app.Activity;
    import android.graphics.Bitmap;
    import android.os.AsyncTask;
    import android.view.Gravity;
    import android.widget.Toast;

    public class GetMethodDemo extends AsyncTask<String, Void, String> {
    String MailTo;
    String Picture;
    Activity bertactivity;
    Bitmap bm;

     public void BitMapFoto(Bitmap bitmap) {
        bm = bitmap;
    }

    //@Override
    protected String doInBackground(String... strings) {

          //http://geekonjava.blogspot.com/2014/03/upload-image-on-server-in-android-using.html

        String dBresultaat = "start";
        try {
            URL url = new URL("http://10.0.2.2:64489/Risico/Risico.asmx/sendMail");

            HttpURLConnection con = (HttpURLConnection) url.openConnection();
            con.setRequestMethod("POST");
            con.setRequestProperty("Content-Type", "application/json");
            con.setRequestProperty("Accept", "application/json");
            con.setDoOutput(true);
            String jsonInputString = "";
            jsonInputString = "{";
             jsonInputString = jsonInputString + "\"MailTo\": \"" + MailTo.toString() + "\",";
            jsonInputString = jsonInputString + "\"Picture\": \"" + Picture.toString() + "\""; 
             //if you take the Picture.toString in debug mode and put it in https://base64.guru/converter/decode/image you see the picture
              jsonInputString = jsonInputString + "}";

            try (OutputStream os = con.getOutputStream()) {
                byte[] input = jsonInputString.getBytes("utf-8");
                os.write(input, 0, input.length);
                int code = con.getResponseCode();
                System.out.println(code);

                try (BufferedReader br = new BufferedReader(new InputStreamReader(con.getInputStream(), "utf-8"))) {
                    StringBuilder response = new StringBuilder();
                    String responseLine = null;
                    while ((responseLine = br.readLine()) != null) {
                        response.append(responseLine.trim());
                    }
                    System.out.println(response.toString());
                    return response.toString();
                }

            } catch (Exception e) {
                e.printStackTrace();
                return "catch twee";
            }
        } catch (Exception e) {
            e.printStackTrace();
            return "catch";
        }
    }

    @Override
    protected void onPreExecute() {
    }

    @Override
    protected void onPostExecute(String s) {
        // super.onPostExecute(s);
        Activity activity = new Bert().activity;
        Toast toast = Toast.makeText(bertactivity, s, Toast.LENGTH_LONG);
        toast.setGravity(Gravity.TOP | Gravity.CENTER_HORIZONTAL, 0, 0);
        toast.show();
    }
    }

你应该在 Framework 4.0 中有你的 web 服务。框架 3.5 不起作用

和 web.config 显示

<configuration>
  
  <system.web.extensions>
    <scripting>
      <webServices>
        <jsonSerialization maxJsonLength="50000000"/>
      </webServices>
    </scripting>
  </system.web.extensions>  
 <system.web>

我的网络方法看起来像这样

[WebMethod()]
public string sendMail(sstring MailTo, string Picture)
{      
    string Resultstring = "";
    int i;
    MailMessage theMessage;
    theMessage = new MailMessage();
    // look if there is an attempt to hack the server
    if ((MailBody.ToUpper()).IndexOf("SELECT") > 0 | (MailBody.ToUpper()).IndexOf("UPDATE") > 0)
    {
        Resultstring = "illegal string";
    }
    else
    {
        theMessage.From = new System.Net.Mail.MailAddress(ConfigurationManager.AppSettings["sender"]); // '"no-reply@taakmonitor.nl")
        try
        {
            theMessage.To.Add(new MailAddress(MailFrom)); // also send a mail to the sender
        }
        catch (Exception ex)
        {
            Resultstring = "Mail address "+ MailFrom + " not ok "; //ex.Message; // als het formaat van het mail adres niet goed is
            theMessage = null;
        }
        String FransGetsCopy = WebConfigurationManager.AppSettings["FransGetsCopy"];

        String[] ToWhom = NullSafeString(MailTo).Split(',');
        for (i = 0; i <= ToWhom.Length - 1; i++)
        {
            try
                {
                   theMessage.To.Add(new MailAddress(ToWhom[i]));
                }
            catch (Exception ex)
                {
                    Resultstring = Resultstring + " mail address " + ToWhom[i] + " not ok "; //ex.Message; // als het formaat van het mail adres niet goed is
                    theMessage = null;
                 }                
        }

        // there should also be a stylesheet
          string StyleText="";
        try
        {
            StyleText = "";
            var data = File.ReadAllText(Server.MapPath("~/App_Data/TextFile.txt"));
            StyleText = data.ToString();   
        }
        catch (Exception)
        {
            Resultstring = Resultstring + " No StyleText available. ";
        }
        theMessage.Subject = MailSubject;
        theMessage.IsBodyHtml = true;
        //the message is created in HTML with the style in the <head> and the MailBody in the body
        theMessage.Body = "<html>" + StyleText + "<body>" + MailBody + "</body></html>";

        // code copied from
        // https://www.codeproject.com/Tips/569532/Submit-Images-to-Web-Service-and-Get-Them-Back
        //in this piece of code I convert the Json picture data to a picture and attach it to the mail
        try
        {
            byte[] data = Convert.FromBase64String(Picture);
            var stream = new MemoryStream(data, 0, data.Length);
            System.Drawing.Image img = System.Drawing.Image.FromStream(stream);
            stream.Seek(0L, SeekOrigin.Begin);
            theMessage.Attachments.Add(new Attachment(stream, "Picture.png"));
            Resultstring = Resultstring +  " image OK";
        }
        catch (Exception ex)
        {
            Resultstring = Resultstring +  " image not OK";
        } 
        SmtpClient MessageObject = new SmtpClient();
        MessageObject.Host = ConfigurationManager.AppSettings["Host"];
        MessageObject.Port = Int32.Parse(ConfigurationManager.AppSettings["Port"]);
        MessageObject.EnableSsl = false;
        MessageObject.Credentials = new System.Net.NetworkCredential(ConfigurationManager.AppSettings["Username"], ConfigurationManager.AppSettings["Password"]);
        try
        {
            MessageObject.Send(theMessage);
            Resultstring = Resultstring +  " mail has been send.";
        }
        catch (Exception ex)
        {
            Resultstring = Resultstring +  " mail has NOT been send.";
        }
        MessageObject = null;
        theMessage = null;
    }
    return Resultstring;
}

最后我在附加的 App_data 文件夹中有一个样式表 TestFile.txt

<head>
    <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-=1">
    <meta content="text/html; charset=us-ascii">
    <style>
        h1{color:blue;}

        .EditText{
            background:#ff0000;/*rood*/
            height:100;
            font-size:10px;
            color:#0000ff;/*blauw*/
        }
        .EditTextVervolg{
            background:#00cc00;/*groen*/
            font-size:20px;
            color:#ffff00;/*geel*/
        }
    </style>
</head>

玩得开心

于 2021-01-31T06:07:27.810 回答