base64 encode HttpPostedFileBase - c#

I want to base64 encode an image that is being received as HttpPostedFileBase to send it in a json object and I don't know how it can be done...and please tell me how can I decode it back to HttpPostedFileBase

I tried this and it worked
string theFileName = Path.GetFileName(YourFile.FileName);
byte[] thePictureAsBytes = new byte[YourFile.ContentLength];
using (BinaryReader theReader = new BinaryReader(YourFile.InputStream))
{
thePictureAsBytes = theReader.ReadBytes(YourFile.ContentLength);
}
string thePictureDataAsString = Convert.ToBase64String(thePictureAsBytes);

Follow the below steps to convert the HttpPostedFileBase to Base64String type
public ActionResult ParseCv(HttpPostedFileBase cvFile)
{
byte[] fileInBytes = new byte[cvFile.ContentLength];
using (BinaryReader theReader = new BinaryReader(cvFile.InputStream))
{
fileInBytes = theReader.ReadBytes(cvFile.ContentLength);
}
string fileAsString= Convert.ToBase64String(fileInBytes);
return Content(fileAsString);
}

You can do this:
byte[] binaryData;
binaryData = new Byte[product.BrochureFile.InputStream.Length];
long bytesRead = product.BrochureFile.InputStream.Read(binaryData, 0, (int)product.BrochureFile.InputStream.Length);
product.BrochureFile.InputStream.Close();
string base64String = System.Convert.ToBase64String(binaryData, 0, binaryData.Length);

Related

convert binary data to gzip file and decompress to a string c#

I am trying to decode binary data that represents a gzip file, I need to decompress the gzip so I can get the nbt (minecraft notation thing) string that is in the gzip, but I keep getting the following error at GZipStream.Read:
The archive entry was compressed using an unsupported compression method.
Does anyone have any idea on how to do this?
This is my code:
public static string Decompress(string input)
{
byte[] compressed = Convert.FromBase64String(input); //This is the binary data
byte[] decompressed = Decompress(compressed);
return Encoding.UTF8.GetString(decompressed);
}
private static byte[] Decompress(byte[] input)
{
using (var source = new MemoryStream(input))
{
byte[] lengthBytes = new byte[4];
source.Read(lengthBytes, 0, 4);
var length = BitConverter.ToInt32(lengthBytes, 0);
using (var decompressionStream = new GZipStream(source,
CompressionMode.Decompress))
{
var result = new byte[length];
decompressionStream.Read(result, 0, length); //Error
return result;
}
}
}
This should do it for you:
public static string Decompress(string value)
{
byte[] buffer = Convert.FromBase64String(value);
byte[] decompressed;
using (var inputStream = new MemoryStream(buffer))
{
using var outputStream = new MemoryStream();
using (var gzip = new GZipStream(inputStream, CompressionMode.Decompress, leaveOpen: true))
{
gzip.CopyTo(outputStream);
}
decompressed = outputStream.ToArray();
}
return Encoding.UTF8.GetString(decompressed);
}

ASP.NET Web API C# Answer HttpRequest with Image via Json [duplicate]

How do you convert an image from a path on the user's computer to a base64 string in C#?
For example, I have the path to the image (in the format C:/image/1.gif) and would like to have a data URI like data:image/gif;base64,/9j/4AAQSkZJRgABAgEAYABgAAD.. representing the 1.gif image returned.
Try this
using (Image image = Image.FromFile(Path))
{
using (MemoryStream m = new MemoryStream())
{
image.Save(m, image.RawFormat);
byte[] imageBytes = m.ToArray();
// Convert byte[] to Base64 String
string base64String = Convert.ToBase64String(imageBytes);
return base64String;
}
}
Get the byte array (byte[]) representation of the image, then use Convert.ToBase64String(), st. like this:
byte[] imageArray = System.IO.File.ReadAllBytes(#"image file path");
string base64ImageRepresentation = Convert.ToBase64String(imageArray);
To convert a base64 image back to a System.Drawing.Image:
var img = Image.FromStream(new MemoryStream(Convert.FromBase64String(base64String)));
Since most of us like oneliners:
Convert.ToBase64String(File.ReadAllBytes(imageFilepath));
If you need it as Base64 byte array:
Encoding.ASCII.GetBytes(Convert.ToBase64String(File.ReadAllBytes(imageFilepath)));
This is the class I wrote for this purpose:
public class Base64Image
{
public static Base64Image Parse(string base64Content)
{
if (string.IsNullOrEmpty(base64Content))
{
throw new ArgumentNullException(nameof(base64Content));
}
int indexOfSemiColon = base64Content.IndexOf(";", StringComparison.OrdinalIgnoreCase);
string dataLabel = base64Content.Substring(0, indexOfSemiColon);
string contentType = dataLabel.Split(':').Last();
var startIndex = base64Content.IndexOf("base64,", StringComparison.OrdinalIgnoreCase) + 7;
var fileContents = base64Content.Substring(startIndex);
var bytes = Convert.FromBase64String(fileContents);
return new Base64Image
{
ContentType = contentType,
FileContents = bytes
};
}
public string ContentType { get; set; }
public byte[] FileContents { get; set; }
public override string ToString()
{
return $"data:{ContentType};base64,{Convert.ToBase64String(FileContents)}";
}
}
var base64Img = new Base64Image {
FileContents = File.ReadAllBytes("Path to image"),
ContentType="image/png"
};
string base64EncodedImg = base64Img.ToString();
You can easily pass the path of the image to retrieve the base64 string
public static string ImageToBase64(string _imagePath)
{
string _base64String = null;
using (System.Drawing.Image _image = System.Drawing.Image.FromFile(_imagePath))
{
using (MemoryStream _mStream = new MemoryStream())
{
_image.Save(_mStream, _image.RawFormat);
byte[] _imageBytes = _mStream.ToArray();
_base64String = Convert.ToBase64String(_imageBytes);
return "data:image/jpg;base64," + _base64String;
}
}
}
Hope this will help.
You can use Server.Map path to give relative path and then you can either create image using base64 conversion or you can just add base64 string to image src.
byte[] imageArray = System.IO.File.ReadAllBytes(Server.MapPath("~/Images/Upload_Image.png"));
string base64ImageRepresentation = Convert.ToBase64String(imageArray);
This code works well with me on DotNet Core 6
using (Image image = Image.FromFile(path))
{
using (MemoryStream m = new MemoryStream())
{
image.Save(m, ImageFormat.Jpeg);
byte[] imageBytes = m.ToArray();
// Convert byte[] to Base64 String
string base64String = Convert.ToBase64String(imageBytes);
// In my case I didn't find the part "data:image/png;base64,", so I added.
return $"data:image/png;base64,{base64String}";
}
}
That way it's simpler, where you pass the image and then pass the format.
private static string ImageToBase64(Image image)
{
var imageStream = new MemoryStream();
try
{
image.Save(imageStream, System.Drawing.Imaging.ImageFormat.Bmp);
imageStream.Position = 0;
var imageBytes = imageStream.ToArray();
var ImageBase64 = Convert.ToBase64String(imageBytes);
return ImageBase64;
}
catch (Exception ex)
{
return "Error converting image to base64!";
}
finally
{
imageStream.Dispose;
}
}
Based on top voted answer, updated for C# 8. Following can be used out of the box. Added explicit System.Drawing before Image as one might be using that class from other namespace defaultly.
public static string ImagePathToBase64(string path)
{
using System.Drawing.Image image = System.Drawing.Image.FromFile(path);
using MemoryStream m = new MemoryStream();
image.Save(m, image.RawFormat);
byte[] imageBytes = m.ToArray();
tring base64String = Convert.ToBase64String(imageBytes);
return base64String;
}
The following piece of code works for me:
string image_path="physical path of your image";
byte[] byes_array = System.IO.File.ReadAllBytes(Server.MapPath(image_path));
string base64String = Convert.ToBase64String(byes_array);
The reverse of this for the googlers arriving here (there is no SO quesion/answer to that)
public static byte[] BytesFromBase64ImageString(string imageData)
{
var trunc = imageData.Split(',')[1];
var padded = trunc.PadRight(trunc.Length + (4 - trunc.Length % 4) % 4, '=');
return Convert.FromBase64String(padded);
}
Something like that
Function imgTo64(ByVal thePath As String) As String
Dim img As System.Drawing.Image = System.Drawing.Image.FromFile(thePath)
Dim m As IO.MemoryStream = New IO.MemoryStream()
img.Save(m, img.RawFormat)
Dim imageBytes As Byte() = m.ToArray
img.Dispose()
Dim str64 = Convert.ToBase64String(imageBytes)
Return str64
End Function

Convert Documents (docs,pdf) to byte array in ASP.NET MVC

I'm having a trouble in converting a Documents to byte array. As of now I don't have a code in it. As I'm having a trouble in finding a right solution. I only have a helper in Converting Image to byte array.
Current code in converting Image to Byte and vice versa
public static Image ConvertBase64ToImage(string base64String)
{
try
{
// Convert Base64 String to byte[]
string res = base64String.Substring(base64String.IndexOf(',') + 1);
byte[] imageBytes = Convert.FromBase64String(res);
MemoryStream ms = new MemoryStream(imageBytes, 0, imageBytes.Length);
// Convert byte[] to Image
ms.Write(imageBytes, 0, imageBytes.Length);
Image image = Image.FromStream(ms, true);
return image;
}
catch
{
return null;
}
}
public static string ConvertImageTo64BaseString(Image image)
{
try
{
using (MemoryStream m = new MemoryStream())
{
image.Save(m, image.RawFormat);
byte[] imageBytes = m.ToArray();
// Convert byte[] to Base64 String
string base64String = Convert.ToBase64String(imageBytes);
return base64String;
}
}
catch
{
return "";
}
}
And the Conversion
Image img = Image.FromStream(file.InputStream, true, true);
Session["userimage"] = "data:image/png;base64," + cHelper.ConvertImageTo64BaseString(img);
C# and .NET already support to read any file content(pdf/excel/image...) into a byte array. Look this example
A: var byteArrayData = File.ReadAllBytes("C:\\file\\myfile.pdf");
Or You can also use FileStream to read all byte contents of your files.
B:
var buffer = new byte[16 * 1024];
using (var stream = new FileStream("C:\\file\\myfile.pdf", FileMode.Open))
{
using (var memoryStream = new MemoryStream())
{
int read;
while ((read = stream.Read(buffer, 0, buffer.Length)) > 0)
{
memoryStream.Write(buffer, 0, read);
}
return memoryStream.ToArray();
}
}

how to convert android.util.Base64.encodeToString to C#

import android.util.Base64;
public static String Base64(String str) {
byte[] data = new byte[0];
data = str.getBytes("UTF-8");
String base64 = Base64.encodeToString(data, 0);
return base64;
}
it is a android method to convert base64
public string Base64(string str)
{
byte[] data = new byte[0];
data = System.Text.Encoding.UTF8.GetBytes(str);
string base64 = Convert.ToBase64String(data);
return base64;
}
it is c# method
but both output are different
what can i do for same output??

Decompress string in java from compressed string in C#

I was searching for the correct solution to decompress the string in java coming from c# code.I tried myself with lot of techniques in java like(gzip,inflatter etc.).but didn't get the solution.i got some error while trying to decompress the string in java from compressed string from c# code.
My C# code to compress the string is,
public static string CompressString(string text)
{
byte[] byteArray = Encoding.GetEncoding(1252).GetBytes(text);// Encoding.ASCII.GetBytes(text);
using (var ms = new MemoryStream())
{
// Compress the text
using (var ds = new DeflateStream(ms, CompressionMode.Compress))
{
ds.Write(byteArray, 0, byteArray.Length);
}
return Convert.ToBase64String(ms.ToArray());
}
}
And decompress the string in java using,
private static void compressAndDecompress(){
try {
// Encode a String into bytes
String string = "xxxxxxSAMPLECOMPRESSEDSTRINGxxxxxxxxxx";
// // Compress the bytes
byte[] decoded = Base64.decodeBase64(string.getBytes());
byte[] output = new byte[4096];
// Decompress the bytes
Inflater decompresser = new Inflater();
decompresser.setInput(decoded);
int resultLength = decompresser.inflate(output);
decompresser.end();
// Decode the bytes into a String
String outputString = new String(output, 0, resultLength, "UTF-8");
System.out.println(outputString);
} catch(java.io.UnsupportedEncodingException ex) {
ex.printStackTrace();
} catch (java.util.zip.DataFormatException ex) {
ex.printStackTrace();
}
}
I get this exception when running the above code:
java.util.zip.DataFormatException: incorrect header check
Kindly give me the sample code in java to decompress the string java.Thanks
My C# code to compress is
private string Compress(string text)
{
byte[] buffer = Encoding.UTF8.GetBytes(text);
MemoryStream ms = new MemoryStream();
using (GZipStream zip = new GZipStream(ms, CompressionMode.Compress, true))
{
zip.Write(buffer, 0, buffer.Length);
}
ms.Position = 0;
MemoryStream outStream = new MemoryStream();
byte[] compressed = new byte[ms.Length];
ms.Read(compressed, 0, compressed.Length);
byte[] gzBuffer = new byte[compressed.Length + 4];
System.Buffer.BlockCopy(compressed, 0, gzBuffer, 4, compressed.Length);
System.Buffer.BlockCopy(BitConverter.GetBytes(buffer.Length), 0, gzBuffer, 0, 4);
return Convert.ToBase64String(gzBuffer);
}
Java code to decompress the text is
private String Decompress(String compressedText)
{
byte[] compressed = compressedText.getBytes("UTF8");
compressed = org.apache.commons.codec.binary.Base64.decodeBase64(compressed);
byte[] buffer=new byte[compressed.length-4];
buffer = copyForDecompression(compressed,buffer, 4, 0);
final int BUFFER_SIZE = 32;
ByteArrayInputStream is = new ByteArrayInputStream(buffer);
GZIPInputStream gis = new GZIPInputStream(is, BUFFER_SIZE);
StringBuilder string = new StringBuilder();
byte[] data = new byte[BUFFER_SIZE];
int bytesRead;
while ((bytesRead = gis.read(data)) != -1)
{
string.append(new String(data, 0, bytesRead));
}
gis.close();
is.close();
return string.toString();
}
private byte[] copyForDecompression(byte[] b1,byte[] b2,int srcoffset,int dstoffset)
{
for(int i=0;i<b2.length && i<b1.length;i++)
{
b2[i]=b1[i+4];
}
return b2;
}
This code works perfectly fine for me.
Had exactly the same issue. Could solve it via
byte[] compressed = Base64Utils.decodeFromString("mybase64encodedandwithc#zippedcrap");
Inflater decompresser = new Inflater(true);
decompresser.setInput(compressed);
byte[] result = new byte[4096];
decompresser.inflate(result);
decompresser.end();
System.out.printf(new String(result));
The magic happens with the boolen parameter on instantiating the Inflator
BW Hubert
For beloved googlers,
As #dbw mentioned,
according to post How to decompress stream deflated with java.util.zip.Deflater in .NET?,
java.util.zip.deflater equivalent in c# the default deflater used in C#
is not having any java equivalent that's why users prefer Gzip, Ziplib
or some other zip techniques.
a relatively simple method would be using GZip.
And for the accepted answer, one problem is that in this method you should append the data size to the compressed string yourself, and more importantly as per my own experience in our production app, It is buggy when the string reaches ~2000 chars!
the bug is in the System.io.Compression.GZipStream
any way using SharpZipLib in c# the problem goes away and everything would be as simple as following snippets:
JAVA:
import android.util.Base64;
import com.google.android.gms.common.util.IOUtils;
import org.jetbrains.annotations.Nullable;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;
public class CompressionHelper {
#Nullable
public static String compress(#Nullable String data) {
if(data == null || data.length() == 0)
return null;
try {
// Create an output stream, and a gzip stream to wrap over.
ByteArrayOutputStream bos = new ByteArrayOutputStream(data.length());
GZIPOutputStream gzip = new GZIPOutputStream(bos);
// Compress the input string
gzip.write(data.getBytes());
gzip.close();
byte[] compressed;
// Convert to base64
compressed = Base64.encode(bos.toByteArray(),Base64.NO_WRAP);
bos.close();
// return the newly created string
return new String(compressed);
} catch(IOException e) {
return null;
}
}
#Nullable
public static String decompress(#Nullable String compressedText) {
if(compressedText == null || compressedText.length() == 0)
return null;
try {
// get the bytes for the compressed string
byte[] compressed = compressedText.getBytes("UTF-8");
// convert the bytes from base64 to normal string
compressed = Base64.decode(compressed, Base64.NO_WRAP);
ByteArrayInputStream bis = new ByteArrayInputStream(compressed);
GZIPInputStream gis = new GZIPInputStream(bis);
byte[] bytes = IOUtils.toByteArray(gis);
return new String(bytes, "UTF-8");
}catch (IOException e){
e.printStackTrace();
}
return null;
}
}
and c#:
using ICSharpCode.SharpZipLib.GZip; //PM> Install-Package SharpZipLib
using System;
using System.Collections.Generic;
using System.IO;
using System.IO.Compression;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace GeneralTools
{
public static class CompressionTools
{
public static string CompressString(string text)
{
if (string.IsNullOrEmpty(text))
return null;
byte[] buffer = Encoding.UTF8.GetBytes(text);
using (var compressedStream = new MemoryStream())
{
GZip.Compress(new MemoryStream(buffer), compressedStream, false);
byte[] compressedData = compressedStream.ToArray();
return Convert.ToBase64String(compressedData);
}
}
public static string DecompressString(string compressedText)
{
if (string.IsNullOrEmpty(compressedText))
return null;
byte[] gZipBuffer = Convert.FromBase64String(compressedText);
using (var memoryStream = new MemoryStream())
{
using (var compressedStream = new MemoryStream(gZipBuffer))
{
var decompressedStream = new MemoryStream();
GZip.Decompress(compressedStream, decompressedStream, false);
return Encoding.UTF8.GetString(decompressedStream.ToArray()).Trim();
}
}
}
}
}
you may also find the codes here
If anyone still interested, here's my full solution with outputstream to handle unknown string size. Using C# DeflateStream and Java Inflater (based on Hubert Ströbitzer answer).
C# Compression:
string CompressString(string raw)
{
byte[] uncompressedData = Encoding.UTF8.GetBytes(raw);
MemoryStream output = new MemoryStream();
using (DeflateStream dStream = new DeflateStream(output, CompressionLevel.Optimal))
{
dStream.Write(uncompressedData, 0, uncompressedData.Length);
}
string compressedString = Convert.ToBase64String(output.ToArray());
return compressedString;
}
Java decompress:
String decompressString(String compressedString) {
byte[] compressed = Base64Utils.decodeFromString(compressedString);
Inflater inflater = new Inflater(true);
inflater.setInput(compressed);
//Using output stream to handle unknown size of decompressed string
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
try {
while(!inflater.finished()){
int count = inflater.inflate(buffer);
outputStream.write(buffer, 0, count);
}
inflater.end();
outputStream.close();
} catch (DataFormatException e) {
//Handle DataFormatException
} catch (IOException e) {
//Handle IOException
}
return outputStream.toString();
}

Categories

Resources